superseedr 1.0.5

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

use tracing::event;
use tracing::Level;

use crate::command::TorrentCommand;
use crate::networking::BlockInfo;
use crate::storage::MultiFileInfo;
use crate::torrent_manager::FileActivityDirection;
use crate::torrent_manager::ManagerEvent;
use crate::tracker::normalize_tracker_urls;

use crate::app::FilePriority;

use tokio::sync::mpsc::Sender;
use tokio::sync::Semaphore;

use std::mem::Discriminant;
use std::net::SocketAddr;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use crate::torrent_file::{Torrent, V2RootInfo};
use crate::torrent_manager::piece_manager::EffectivePiecePriority;
use crate::torrent_manager::piece_manager::PieceManager;
use crate::torrent_manager::piece_manager::PieceStatus;
use crate::torrent_manager::FileActivityUpdate;
use std::collections::{HashMap, HashSet};

const MAX_TIMEOUT_COUNT: u32 = 10;
const SMOOTHING_PERIOD_MS: f64 = 5000.0;
const PEER_UPLOAD_IN_FLIGHT_LIMIT: usize = 16;
const MAX_BLOCK_SIZE: u32 = 131_072;
const UPLOAD_SLOTS_DEFAULT: usize = 4;
const DEFAULT_ANNOUNCE_INTERVAL_SECS: u64 = 60;
pub const MAX_PIPELINE_DEPTH: usize = 512;

// Quality gate: once we have this many connected peers, pause admitting new peers
// to avoid churn storms. This is intentionally independent of resource-manager limits.
const PEER_ADMISSION_QUALITY_THRESHOLD: usize = 400;

pub type PeerAddr = SocketAddr;

#[derive(Debug, Clone)]
pub enum Action {
    TorrentManagerInit {
        is_paused: bool,
        announce_immediately: bool,
    },
    Tick {
        dt_ms: u64,
    },
    RecalculateChokes {
        random_seed: u64,
    },
    CheckCompletion,
    AssignWork {
        peer_id: String,
    },
    ConnectToWebSeeds,
    RegisterPeer {
        peer_id: String,
        tx: Sender<TorrentCommand>,
    },
    PeerSuccessfullyConnected {
        peer_id: String,
    },
    PeerDisconnected {
        peer_id: String,
        force: bool,
    },
    UpdatePeerId {
        peer_addr: String,
        new_id: Vec<u8>,
    },
    PeerBitfieldReceived {
        peer_id: String,
        bitfield: Vec<u8>,
    },
    PeerChoked {
        peer_id: String,
    },
    PeerUnchoked {
        peer_id: String,
    },
    PeerInterested {
        peer_id: String,
    },
    PeerHavePiece {
        peer_id: String,
        piece_index: u32,
    },
    IncomingBlock {
        peer_id: String,
        piece_index: u32,
        block_offset: u32,
        data: Vec<u8>,
    },
    PieceVerified {
        peer_id: String,
        piece_index: u32,
        valid: bool,
        data: Vec<u8>,
    },
    PieceWrittenToDisk {
        peer_id: String,
        piece_index: u32,
    },
    PieceWriteFailed {
        piece_index: u32,
    },
    RequestUpload {
        peer_id: String,
        piece_index: u32,
        block_offset: u32,
        length: u32,
    },
    TrackerResponse {
        url: String,
        peers: Vec<PeerAddr>,
        interval: u64,
        min_interval: Option<u64>,
    },
    TrackerError {
        url: String,
    },
    PeerConnectionFailed {
        peer_addr: String,
    },
    MetadataReceived {
        torrent: Box<Torrent>,
        metadata_length: i64,
    },
    MerkleProofReceived {
        peer_id: String,
        piece_index: u32,
        proof: Vec<u8>,
    },
    ValidationComplete {
        completed_pieces: Vec<u32>,
    },

    BlockSentToPeer {
        peer_id: String,
        byte_count: u64,
    },

    CancelUpload {
        peer_id: String,
        piece_index: u32,
        block_offset: u32,
        length: u32,
    },

    Cleanup,
    Pause,
    Resume,
    Delete,
    UpdateListenPort,
    SetUserTorrentConfig {
        torrent_data_path: PathBuf,
        file_priorities: HashMap<usize, FilePriority>,
        container_name: Option<String>,
    },
    SetDataAvailability {
        available: bool,
    },
    ValidationProgress {
        count: u32,
    },
    Shutdown,
    FatalError,
}

#[derive(Debug)]
#[must_use]
pub enum Effect {
    DoNothing,
    EmitMetrics {
        bytes_dl: u64,
        bytes_ul: u64,
        file_activity_updates: Vec<FileActivityUpdate>,
    },
    EmitManagerEvent(ManagerEvent),
    SendToPeer {
        peer_id: String,
        cmd: Box<TorrentCommand>,
    },
    DisconnectPeerSession {
        peer_id: String,
        peer_tx: Sender<TorrentCommand>,
    },
    DisconnectPeer {
        peer_id: String,
    },
    AnnounceCompleted {
        url: String,
    },

    // --- New I/O & Work Effects ---
    VerifyPiece {
        peer_id: String,
        piece_index: u32,
        data: Vec<u8>,
    },
    VerifyPieceV2 {
        peer_id: String,
        piece_index: u32,
        proof: Vec<u8>,
        data: Vec<u8>,
        root_hash: Vec<u8>,
        _file_start_offset: u64,
        valid_length: usize,
        relative_index: u32,
        hashing_context_len: usize,
    },
    WriteToDisk {
        peer_id: String,
        piece_index: u32,
        data: Vec<u8>,
    },
    ReadFromDisk {
        peer_id: String,
        block_info: BlockInfo,
    },
    BroadcastHave {
        piece_index: u32,
    },
    ConnectToPeer {
        addr: SocketAddr,
    },
    RequestHashes {
        peer_id: String,
        file_root: Vec<u8>,
        piece_index: u32,
        length: u32,
        proof_layers: u32,
        base_layer: u32,
    },

    StartWebSeed {
        url: String,
    },

    StartValidation,
    AnnounceToTracker {
        url: String,
    },

    ConnectToPeersFromTrackers,

    AbortUpload {
        peer_id: String,
        block_info: BlockInfo,
    },

    ClearAllUploads,
    DeleteFiles {
        files: Vec<PathBuf>,
        directories: Vec<PathBuf>,
    },
    TriggerDhtSearch,
    PrepareShutdown {
        tracker_urls: Vec<String>,
        left: usize,
        uploaded: usize,
        downloaded: usize,
    },
}

#[derive(Debug, Clone)]
pub struct TrackerState {
    pub next_announce_time: Instant,
    pub leeching_interval: Option<Duration>,
    pub seeding_interval: Option<Duration>,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub enum TorrentActivity {
    #[default]
    Initializing,
    Paused,
    ConnectingToPeers,
    RequestingPieces,
    DownloadingPiece(u32),
    SendingPiece(u32),
    VerifyingPiece(u32),
    AnnouncingToTracker,
    ProcessingPeers(usize),

    #[cfg(feature = "dht")]
    SearchingDht,
}

#[derive(PartialEq, Debug, Default, Clone)]
pub enum TorrentStatus {
    #[default]
    AwaitingMetadata,
    Validating,
    Standard,
    Endgame,
    Done,
}

#[derive(PartialEq, Debug, Clone)]
pub enum ChokeStatus {
    Choke,
    Unchoke,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FileActivityInterval {
    start: u64,
    end: u64,
}

#[derive(Debug, Clone)]
pub struct TorrentState {
    pub info_hash: Vec<u8>,
    pub torrent: Option<Torrent>,
    pub torrent_metadata_length: Option<i64>,
    pub is_paused: bool,
    pub torrent_status: TorrentStatus,
    pub torrent_validation_status: bool,
    pub last_activity: TorrentActivity,
    pub has_made_first_connection: bool,
    pub session_total_uploaded: u64,
    pub session_total_downloaded: u64,
    pub bytes_downloaded_in_interval: u64,
    pub bytes_uploaded_in_interval: u64,
    pub total_dl_prev_avg_ema: f64,
    pub total_ul_prev_avg_ema: f64,
    pub number_of_successfully_connected_peers: usize,
    pub peers: HashMap<String, PeerState>,
    pub piece_manager: PieceManager,
    pub trackers: HashMap<String, TrackerState>,
    pub timed_out_peers: HashMap<String, (u32, Instant)>,
    pub last_known_peers: HashSet<String>,
    pub optimistic_unchoke_timer: Option<Instant>,
    pub validation_pieces_found: u32,
    pub now: Instant,
    pub has_started_announce_sent: bool,
    pub v2_proofs: HashMap<u32, Vec<u8>>,
    pub v2_pending_data: HashMap<u32, (u32, Vec<u8>)>,
    pub piece_to_roots: HashMap<u32, Vec<V2RootInfo>>,
    pub verifying_pieces: HashSet<u32>,
    pub torrent_data_path: Option<PathBuf>,
    pub container_name: Option<String>,
    pub multi_file_info: Option<MultiFileInfo>,
    pub file_priorities: HashMap<usize, FilePriority>,
    pub data_available: bool,
    pub pending_disconnects: Vec<String>,
    pub pending_failures: Vec<String>,
    pub accepting_new_peers: bool,
    pending_download_file_activity: Vec<FileActivityInterval>,
    pending_upload_file_activity: Vec<FileActivityInterval>,
}
impl Default for TorrentState {
    fn default() -> Self {
        Self {
            info_hash: Vec::new(),
            torrent: None,
            torrent_metadata_length: None,
            is_paused: false,
            torrent_status: TorrentStatus::default(),
            torrent_validation_status: false,
            last_activity: TorrentActivity::default(),
            has_made_first_connection: false,
            session_total_uploaded: 0,
            session_total_downloaded: 0,
            bytes_downloaded_in_interval: 0,
            bytes_uploaded_in_interval: 0,
            total_dl_prev_avg_ema: 0.0,
            total_ul_prev_avg_ema: 0.0,
            number_of_successfully_connected_peers: 0,
            peers: HashMap::new(),
            piece_manager: PieceManager::new(),
            trackers: HashMap::new(),
            timed_out_peers: HashMap::new(),
            last_known_peers: HashSet::new(),
            optimistic_unchoke_timer: None,
            validation_pieces_found: 0,
            now: Instant::now(),
            has_started_announce_sent: false,
            v2_proofs: HashMap::new(),
            v2_pending_data: HashMap::new(),
            piece_to_roots: HashMap::new(),
            verifying_pieces: HashSet::new(),
            torrent_data_path: None,
            container_name: None,
            multi_file_info: None,
            file_priorities: HashMap::new(),
            data_available: true,
            pending_disconnects: Vec::with_capacity(100),
            pending_failures: Vec::with_capacity(100),
            accepting_new_peers: true,
            pending_download_file_activity: Vec::with_capacity(64),
            pending_upload_file_activity: Vec::with_capacity(64),
        }
    }
}

impl TorrentState {
    pub fn new(
        info_hash: Vec<u8>,
        torrent: Option<Torrent>,
        torrent_metadata_length: Option<i64>,
        piece_manager: PieceManager,
        trackers: HashMap<String, TrackerState>,
        torrent_validation_status: bool,
        container_name: Option<String>,
    ) -> Self {
        let torrent_status = if torrent.is_some() {
            TorrentStatus::Validating
        } else {
            TorrentStatus::AwaitingMetadata
        };

        let mut state = Self {
            info_hash,
            torrent,
            torrent_metadata_length,
            torrent_status,
            piece_manager,
            trackers,
            torrent_validation_status,
            container_name,
            optimistic_unchoke_timer: Some(
                Instant::now()
                    .checked_sub(Duration::from_secs(31))
                    .unwrap_or(Instant::now()),
            ),
            now: Instant::now(),
            ..Default::default()
        };

        // Populate V2 Maps Immediately
        // This ensures AssignWork has the data it needs to clamp requests from the very start.
        let (v2_piece_count, piece_overrides) = state.rebuild_v2_mappings();

        if let Some(ref t) = state.torrent {
            let total_len: u64 = if t.info.meta_version == Some(2) {
                // V2: Geometry is aligned to piece boundaries
                let num_pieces = if !t.info.pieces.is_empty() {
                    t.info.pieces.len() / 20
                } else if v2_piece_count > 0 {
                    // Use the count we just calculated
                    v2_piece_count as usize
                } else {
                    0
                };
                (num_pieces as u64) * (t.info.piece_length as u64)
            } else {
                // V1: Geometry is packed (sum of files)
                if t.info.files.is_empty() {
                    t.info.length as u64
                } else {
                    t.info.files.iter().map(|f| f.length as u64).sum()
                }
            };

            state.piece_manager.set_geometry(
                t.info.piece_length as u32,
                total_len,
                piece_overrides,
                torrent_validation_status,
            );
        }

        state
    }

    fn get_piece_size(&self, piece_index: u32) -> usize {
        if let Some(torrent) = &self.torrent {
            let piece_len = torrent.info.piece_length as u64;

            // V2 Logic: Clamp size to the specific file length
            if let Some(roots) = self.piece_to_roots.get(&piece_index) {
                // In V2, pieces align to files. We check the mapped file for this piece.
                if let Some(root_info) = roots.first() {
                    let global_piece_start = piece_index as u64 * piece_len;

                    // Calculate offset relative to the start of this specific file
                    let offset_in_file = global_piece_start.saturating_sub(root_info.file_offset);

                    // The piece cannot exceed the remaining bytes in this file
                    let remaining_in_file = root_info.length.saturating_sub(offset_in_file);

                    return std::cmp::min(piece_len, remaining_in_file) as usize;
                }
            }

            // Fallback (V1 / Standard contiguous stream logic)
            let total_len: u64 = if !torrent.info.files.is_empty() {
                torrent.info.files.iter().map(|f| f.length as u64).sum()
            } else {
                torrent.info.length as u64
            };

            let offset = piece_index as u64 * piece_len;
            let remaining = total_len.saturating_sub(offset);
            std::cmp::min(piece_len, remaining) as usize
        } else {
            0
        }
    }

    pub fn update(&mut self, action: Action) -> Vec<Effect> {
        match action {
            Action::TorrentManagerInit {
                is_paused,
                announce_immediately,
            } => {
                let mut effects = Vec::new();

                self.is_paused = is_paused;
                if self.is_paused {
                    return effects;
                }

                effects.extend(self.update(Action::ConnectToWebSeeds));

                let should_announce =
                    announce_immediately || self.torrent_status == TorrentStatus::AwaitingMetadata;
                if should_announce {
                    for url in self.trackers.keys() {
                        effects.push(Effect::AnnounceToTracker { url: url.clone() });
                    }
                    self.has_started_announce_sent = true;
                }

                effects
            }
            Action::Tick { dt_ms } => {
                self.now += Duration::from_millis(dt_ms);
                self.refresh_peer_admission_guard();
                let scaling_factor = if dt_ms > 0 {
                    1000.0 / dt_ms as f64
                } else {
                    1.0
                };
                let dt = dt_ms as f64;
                // Calculate Alpha for Exponential Moving Average
                let alpha = 1.0 - (-dt / SMOOTHING_PERIOD_MS).exp();

                let inst_total_dl_speed =
                    (self.bytes_downloaded_in_interval as f64 * 8.0) * scaling_factor;
                let inst_total_ul_speed =
                    (self.bytes_uploaded_in_interval as f64 * 8.0) * scaling_factor;

                // Capture values for the EmitMetrics event
                let dl_tick = self.bytes_downloaded_in_interval;
                let ul_tick = self.bytes_uploaded_in_interval;

                // Reset interval counters
                self.bytes_downloaded_in_interval = 0;
                self.bytes_uploaded_in_interval = 0;

                // Update Global EMAs
                self.total_dl_prev_avg_ema =
                    (inst_total_dl_speed * alpha) + (self.total_dl_prev_avg_ema * (1.0 - alpha));
                self.total_ul_prev_avg_ema =
                    (inst_total_ul_speed * alpha) + (self.total_ul_prev_avg_ema * (1.0 - alpha));

                for peer in self.peers.values_mut() {
                    let inst_dl_speed =
                        (peer.bytes_downloaded_in_tick as f64 * 8.0) * scaling_factor;
                    let inst_ul_speed = (peer.bytes_uploaded_in_tick as f64 * 8.0) * scaling_factor;

                    // Update Peer EMAs
                    peer.prev_avg_dl_ema =
                        (inst_dl_speed * alpha) + (peer.prev_avg_dl_ema * (1.0 - alpha));
                    peer.download_speed_bps = peer.prev_avg_dl_ema as u64;

                    peer.prev_avg_ul_ema =
                        (inst_ul_speed * alpha) + (peer.prev_avg_ul_ema * (1.0 - alpha));
                    peer.upload_speed_bps = peer.prev_avg_ul_ema as u64;

                    // Reset Peer tick counters
                    peer.bytes_downloaded_in_tick = 0;
                    peer.bytes_uploaded_in_tick = 0;
                }

                let mut effects = vec![Effect::EmitMetrics {
                    bytes_dl: dl_tick,
                    bytes_ul: ul_tick,
                    file_activity_updates: self.drain_file_activity_updates(),
                }];

                if self.torrent_status == TorrentStatus::Validating || self.is_paused {
                    return effects;
                }

                // Tracker Announce Logic
                for (url, tracker) in self.trackers.iter_mut() {
                    if self.now >= tracker.next_announce_time {
                        self.last_activity = TorrentActivity::AnnouncingToTracker;
                        let interval = if self.torrent_status == TorrentStatus::Done {
                            tracker
                                .seeding_interval
                                .unwrap_or(Duration::from_secs(DEFAULT_ANNOUNCE_INTERVAL_SECS))
                        } else {
                            tracker
                                .leeching_interval
                                .unwrap_or(Duration::from_secs(DEFAULT_ANNOUNCE_INTERVAL_SECS))
                        };
                        tracker.next_announce_time = self.now + interval;
                        effects.push(Effect::AnnounceToTracker { url: url.clone() });
                    }
                }

                effects
            }

            Action::RecalculateChokes { random_seed } => {
                let mut effects = Vec::new();
                let mut unchoke_candidates = HashSet::new();

                if self.data_available {
                    let mut interested_peers: Vec<&mut PeerState> = self
                        .peers
                        .values_mut()
                        .filter(|p| p.peer_is_interested_in_us)
                        .collect();

                    if self.torrent_status == TorrentStatus::Done {
                        interested_peers.sort_by(|a, b| {
                            b.bytes_uploaded_to_peer.cmp(&a.bytes_uploaded_to_peer)
                        });
                    } else {
                        interested_peers.sort_by(|a, b| {
                            b.bytes_downloaded_from_peer
                                .cmp(&a.bytes_downloaded_from_peer)
                        });
                    }

                    unchoke_candidates = interested_peers
                        .iter()
                        .take(UPLOAD_SLOTS_DEFAULT)
                        .map(|p| p.ip_port.clone())
                        .collect();

                    if self.optimistic_unchoke_timer.is_some_and(|t| {
                        self.now.saturating_duration_since(t) > Duration::from_secs(30)
                    }) {
                        let optimistic_candidates: Vec<&mut PeerState> = interested_peers
                            .into_iter()
                            .filter(|p| !unchoke_candidates.contains(&p.ip_port))
                            .collect();

                        if !optimistic_candidates.is_empty() {
                            let idx = (random_seed as usize) % optimistic_candidates.len();
                            let chosen_id = optimistic_candidates[idx].ip_port.clone();
                            unchoke_candidates.insert(chosen_id);
                        }

                        self.optimistic_unchoke_timer = Some(self.now);
                    }
                }

                for peer in self.peers.values_mut() {
                    if unchoke_candidates.contains(&peer.ip_port) {
                        if peer.am_choking == ChokeStatus::Choke {
                            peer.am_choking = ChokeStatus::Unchoke;
                            effects.push(Effect::SendToPeer {
                                peer_id: peer.ip_port.clone(),
                                cmd: Box::new(TorrentCommand::PeerUnchoke),
                            });
                        }
                    } else if peer.am_choking == ChokeStatus::Unchoke {
                        peer.am_choking = ChokeStatus::Choke;
                        effects.push(Effect::SendToPeer {
                            peer_id: peer.ip_port.clone(),
                            cmd: Box::new(TorrentCommand::PeerChoke),
                        });
                    }

                    peer.bytes_downloaded_from_peer = 0;
                    peer.bytes_uploaded_to_peer = 0;
                }

                if effects.is_empty() {
                    vec![Effect::DoNothing]
                } else {
                    effects
                }
            }

            Action::CheckCompletion => {
                if self.torrent_status == TorrentStatus::AwaitingMetadata
                    || self.torrent_status == TorrentStatus::Validating
                    || self.torrent_status == TorrentStatus::Done
                {
                    return vec![Effect::DoNothing];
                }

                let is_complete = if self.piece_manager.piece_priorities.is_empty() {
                    self.piece_manager
                        .bitfield
                        .iter()
                        .all(|&s| s == PieceStatus::Done)
                } else {
                    self.piece_manager
                        .bitfield
                        .iter()
                        .enumerate()
                        .all(|(i, status)| {
                            if *status == PieceStatus::Done {
                                return true;
                            }
                            self.piece_manager.piece_priorities[i] == EffectivePiecePriority::Skip
                        })
                };

                let has_pieces = !self.piece_manager.bitfield.is_empty();

                if is_complete && has_pieces {
                    let mut effects = Vec::new();
                    self.torrent_status = TorrentStatus::Done;

                    self.piece_manager.need_queue.clear();
                    self.piece_manager.pending_queue.clear();
                    self.piece_manager.clear_assembly_buffers();

                    for peer in self.peers.values_mut() {
                        peer.pending_requests.clear();
                        peer.active_blocks.clear();
                        peer.inflight_requests = 0;

                        if peer.am_interested {
                            peer.am_interested = false;
                            effects.push(Effect::SendToPeer {
                                peer_id: peer.ip_port.clone(),
                                cmd: Box::new(TorrentCommand::NotInterested),
                            });
                        }
                    }

                    // 4. NOTIFY TRACKER
                    // Logic: Only send "event=completed" if we physically possess 100% of the bits.
                    // If we skipped files (Priority Mode), we are "Done" locally but not "Completed" globally.
                    let physically_complete = self
                        .piece_manager
                        .bitfield
                        .iter()
                        .all(|&s| s == PieceStatus::Done);

                    if physically_complete {
                        for (url, tracker) in self.trackers.iter_mut() {
                            tracker.next_announce_time = self.now;
                            effects.push(Effect::AnnounceCompleted { url: url.clone() });
                        }
                    } else {
                        // Priority Mode (Partial Completion): Just send a regular update so the tracker knows we stopped downloading.
                        for (url, tracker) in self.trackers.iter_mut() {
                            tracker.next_announce_time = self.now;
                            effects.push(Effect::AnnounceToTracker { url: url.clone() });
                        }
                    }

                    return effects;
                }

                vec![Effect::DoNothing]
            }

            Action::AssignWork { peer_id } => {
                if self.torrent_status == TorrentStatus::Validating {
                    return vec![Effect::DoNothing];
                }
                if self.piece_manager.bitfield.is_empty() {
                    return vec![Effect::DoNothing];
                }
                if self.torrent_data_path.is_none() {
                    return vec![Effect::DoNothing];
                }
                if self.piece_manager.need_queue.is_empty()
                    && self.piece_manager.pending_queue.is_empty()
                {
                    return vec![Effect::DoNothing];
                }
                if self.torrent.is_none() {
                    return vec![Effect::DoNothing];
                }

                // Prepare size calculation closure with disjoint borrows.
                let torrent_ref = &self.torrent;
                let roots_ref = &self.piece_to_roots;

                let calc_v2_limit = |piece_index: u32| -> Option<u32> {
                    if let Some(torrent) = torrent_ref {
                        let piece_len = torrent.info.piece_length as u64;
                        if let Some(roots) = roots_ref.get(&piece_index) {
                            if let Some(root_info) = roots.first() {
                                let global_piece_start = piece_index as u64 * piece_len;
                                let offset_in_file =
                                    global_piece_start.saturating_sub(root_info.file_offset);
                                let remaining_in_file =
                                    root_info.length.saturating_sub(offset_in_file);
                                return Some(std::cmp::min(piece_len, remaining_in_file) as u32);
                            }
                        }
                        None
                    } else {
                        None
                    }
                };

                let mut effects = Vec::new();
                let mut request_batch = Vec::new();

                let peer_opt = self.peers.get_mut(&peer_id);
                if peer_opt.is_none() {
                    return effects;
                }
                let peer = peer_opt.unwrap();

                let has_needed_pieces = !peer.bitfield.is_empty()
                    && (self
                        .piece_manager
                        .need_queue
                        .iter()
                        .any(|&p| peer.bitfield.get(p as usize) == Some(&true))
                        || self
                            .piece_manager
                            .pending_queue
                            .keys()
                            .any(|&p| peer.bitfield.get(p as usize) == Some(&true)));

                let has_pending_requests = !peer.pending_requests.is_empty();
                let should_be_interested = has_needed_pieces || has_pending_requests;

                if should_be_interested && !peer.am_interested {
                    peer.am_interested = true;
                    effects.push(Effect::SendToPeer {
                        peer_id: peer_id.clone(),
                        cmd: Box::new(TorrentCommand::ClientInterested),
                    });
                } else if !should_be_interested && peer.am_interested {
                    peer.am_interested = false;
                    effects.push(Effect::SendToPeer {
                        peer_id: peer_id.clone(),
                        cmd: Box::new(TorrentCommand::NotInterested),
                    });
                }

                if peer.peer_choking == ChokeStatus::Choke {
                    return effects;
                }
                if peer.bitfield.is_empty() {
                    return effects;
                }

                let current_inflight = peer.inflight_requests;
                let max_depth = MAX_PIPELINE_DEPTH;

                if current_inflight >= max_depth {
                    return effects;
                }
                let mut available_slots = max_depth - current_inflight;

                let mut pending_pieces: Vec<u32> = peer.pending_requests.iter().cloned().collect();
                pending_pieces.sort();

                for piece_index in pending_pieces {
                    if available_slots == 0 {
                        break;
                    }
                    if self.verifying_pieces.contains(&piece_index) {
                        continue;
                    }
                    let block_addrs = self
                        .piece_manager
                        .requestable_block_addresses_for_piece(piece_index);

                    for addr in block_addrs {
                        if available_slots == 0 {
                            break;
                        }

                        let final_len = if let Some(limit) = calc_v2_limit(addr.piece_index) {
                            let remaining = limit.saturating_sub(addr.byte_offset);
                            std::cmp::min(addr.length, remaining)
                        } else {
                            addr.length
                        };

                        if final_len == 0 {
                            continue;
                        }

                        // Is peer already working on it?
                        if peer.active_blocks.contains(&(
                            addr.piece_index,
                            addr.byte_offset,
                            final_len,
                        )) {
                            continue;
                        }

                        request_batch.push((addr.piece_index, addr.byte_offset, final_len));
                        peer.active_blocks
                            .insert((addr.piece_index, addr.byte_offset, final_len));

                        available_slots -= 1;
                    }
                }

                let candidate_pool: Box<dyn Iterator<Item = &u32> + '_> =
                    if self.torrent_status == TorrentStatus::Endgame {
                        Box::new(
                            self.piece_manager
                                .need_queue
                                .iter()
                                .chain(self.piece_manager.pending_queue.keys()),
                        )
                    } else {
                        Box::new(self.piece_manager.need_queue.iter())
                    };

                let mut valid_candidates: Vec<u32> = candidate_pool
                    .copied()
                    .filter(|&p_idx| {
                        // Peer must have the piece
                        if peer.bitfield.get(p_idx as usize) != Some(&true) {
                            return false;
                        }
                        // Don't duplicate work currently verifying
                        if self.verifying_pieces.contains(&p_idx) {
                            return false;
                        }
                        // Don't request what we already asked this specific peer for
                        if peer.pending_requests.contains(&p_idx) {
                            return false;
                        }
                        true
                    })
                    .collect();

                // Sort ascending: Lower availability count = Rarer = Higher Priority
                valid_candidates.sort_by_key(|&p_idx| {
                    // FIX: Call the helper method we just created
                    self.piece_manager.get_piece_availability(p_idx)
                });

                let pieces_to_request = valid_candidates.into_iter().take(available_slots);

                for piece_index in pieces_to_request {
                    if available_slots == 0 {
                        break;
                    }

                    // --- A. Update State ---
                    self.piece_manager
                        .mark_as_pending(piece_index, peer_id.clone());
                    peer.pending_requests.insert(piece_index);

                    if self.piece_manager.need_queue.is_empty()
                        && self.torrent_status != TorrentStatus::Endgame
                    {
                        self.torrent_status = TorrentStatus::Endgame;
                    }

                    // --- B. Generate Block Requests ---
                    let block_addrs = self
                        .piece_manager
                        .requestable_block_addresses_for_piece(piece_index);

                    for addr in block_addrs {
                        if available_slots == 0 {
                            break;
                        }

                        let final_len = if let Some(limit) = calc_v2_limit(addr.piece_index) {
                            let remaining = limit.saturating_sub(addr.byte_offset);
                            std::cmp::min(addr.length, remaining)
                        } else {
                            addr.length
                        };

                        if final_len == 0 {
                            continue;
                        }

                        if peer.active_blocks.contains(&(
                            addr.piece_index,
                            addr.byte_offset,
                            final_len,
                        )) {
                            continue;
                        }

                        request_batch.push((addr.piece_index, addr.byte_offset, final_len));
                        peer.active_blocks
                            .insert((addr.piece_index, addr.byte_offset, final_len));

                        available_slots -= 1;
                    }
                }

                if !request_batch.is_empty() {
                    if !matches!(self.last_activity, TorrentActivity::DownloadingPiece(_)) {
                        self.last_activity = TorrentActivity::RequestingPieces;
                    }

                    peer.inflight_requests += request_batch.len();
                    effects.push(Effect::SendToPeer {
                        peer_id: peer_id.clone(),
                        cmd: Box::new(TorrentCommand::BulkRequest(request_batch)),
                    });
                }

                effects
            }

            Action::ConnectToWebSeeds => {
                let mut effects = Vec::new();
                if let Some(torrent) = &self.torrent {
                    if let Some(urls) = &torrent.url_list {
                        for url in urls {
                            effects.push(Effect::StartWebSeed { url: url.clone() });
                        }
                    }
                }
                effects
            }

            Action::RegisterPeer { peer_id, tx } => {
                if !self.peers.contains_key(&peer_id) {
                    let mut peer_state = PeerState::new(peer_id.clone(), tx, self.now);
                    peer_state.peer_id = peer_id.as_bytes().to_vec();
                    self.peers.insert(peer_id, peer_state);
                    // Admission pressure should react to discovered/registered peers immediately,
                    // not only after handshake success.
                    self.number_of_successfully_connected_peers = self.peers.len();
                    self.refresh_peer_admission_guard();
                }
                vec![Effect::DoNothing]
            }

            // --- Peer Lifecycle Actions ---
            Action::PeerSuccessfullyConnected { peer_id } => {
                self.timed_out_peers.remove(&peer_id);

                if !self.has_made_first_connection {
                    self.has_made_first_connection = true;
                }

                self.number_of_successfully_connected_peers = self.peers.len();
                self.refresh_peer_admission_guard();

                vec![Effect::EmitManagerEvent(ManagerEvent::PeerConnected {
                    info_hash: self.info_hash.clone(),
                })]
            }

            Action::PeerDisconnected { peer_id, force } => {
                if !peer_id.is_empty() && self.peers.contains_key(&peer_id) {
                    self.pending_disconnects.push(peer_id);
                }

                if !force && self.pending_disconnects.len() < 50 {
                    return vec![Effect::DoNothing];
                }

                if self.pending_disconnects.is_empty() {
                    return vec![Effect::DoNothing];
                }

                let mut effects = Vec::new();
                let batch = std::mem::take(&mut self.pending_disconnects);

                self.last_activity = TorrentActivity::ProcessingPeers(self.peers.len());

                for pid in batch {
                    if let Some(removed_peer) = self.peers.remove(&pid) {
                        for piece_index in removed_peer.pending_requests {
                            if self.piece_manager.bitfield.get(piece_index as usize)
                                != Some(&PieceStatus::Done)
                            {
                                self.piece_manager.requeue_pending_to_need(piece_index);
                            }
                        }
                        effects.push(Effect::DisconnectPeer { peer_id: pid });
                        effects.push(Effect::EmitManagerEvent(ManagerEvent::PeerDisconnected {
                            info_hash: self.info_hash.clone(),
                        }));
                    }
                }

                self.number_of_successfully_connected_peers = self.peers.len();
                self.refresh_peer_admission_guard();

                effects
            }

            Action::UpdatePeerId { peer_addr, new_id } => {
                if let Some(peer) = self.peers.get_mut(&peer_addr) {
                    peer.peer_id = new_id;
                }
                vec![Effect::DoNothing]
            }

            Action::PeerBitfieldReceived { peer_id, bitfield } => {
                let mut effects = Vec::new();

                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    // Peer is misbehaving (sending 2nd bitfield). Disconnect them.
                    if !peer.bitfield.is_empty() && peer.bitfield.iter().any(|&b| b) {
                        effects.push(Effect::DisconnectPeer {
                            peer_id: peer_id.clone(),
                        });
                        return effects;
                    }

                    peer.bitfield = bitfield
                        .iter()
                        .flat_map(|&byte| (0..8).map(move |i| (byte >> (7 - i)) & 1 == 1))
                        .collect();

                    let total_pieces = self.piece_manager.bitfield.len();

                    if total_pieces > 0 {
                        if peer.bitfield.len() > total_pieces {
                            peer.bitfield.truncate(total_pieces);
                        } else if peer.bitfield.len() < total_pieces {
                            peer.bitfield.resize(total_pieces, false);
                        }
                    }
                }

                self.update(Action::AssignWork { peer_id })
            }

            Action::PeerChoked { peer_id } => {
                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    peer.inflight_requests = 0;
                    peer.active_blocks.clear();
                    peer.peer_choking = ChokeStatus::Choke;

                    let pieces_to_requeue = std::mem::take(&mut peer.pending_requests);
                    for piece_index in pieces_to_requeue {
                        if self.piece_manager.bitfield.get(piece_index as usize)
                            != Some(&PieceStatus::Done)
                        {
                            self.piece_manager.requeue_pending_to_need(piece_index);
                        }
                    }
                }

                vec![Effect::DoNothing]
            }

            Action::PeerUnchoked { peer_id } => {
                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    peer.peer_choking = ChokeStatus::Unchoke;
                }
                self.update(Action::AssignWork { peer_id })
            }

            Action::PeerInterested { peer_id } => {
                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    peer.peer_is_interested_in_us = true;
                }
                vec![Effect::DoNothing]
            }

            Action::PeerHavePiece {
                peer_id,
                piece_index,
            } => {
                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    if (piece_index as usize) < peer.bitfield.len() {
                        peer.bitfield[piece_index as usize] = true;
                    }
                }
                self.update(Action::AssignWork { peer_id })
            }

            // --- Data Flow (The Core Logic) ---
            Action::IncomingBlock {
                peer_id,
                piece_index,
                block_offset,
                data,
            } => {
                if piece_index as usize >= self.piece_manager.bitfield.len() {
                    return vec![Effect::DoNothing];
                }

                let mut effects = Vec::new();
                let len = data.len() as u64;

                // Determine if this block is actually needed (not redundant).
                // We perform accounting only for useful blocks to prevent metric inflation.
                let is_piece_done = self.piece_manager.bitfield.get(piece_index as usize)
                    == Some(&PieceStatus::Done);

                if !is_piece_done {
                    self.bytes_downloaded_in_interval =
                        self.bytes_downloaded_in_interval.saturating_add(len);
                    self.session_total_downloaded =
                        self.session_total_downloaded.saturating_add(len);
                }

                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    // CRITICAL: Always decrement inflight requests, even for redundant blocks.
                    // If we don't, the pipeline counts never decrease, causing a stall.
                    peer.inflight_requests = peer.inflight_requests.saturating_sub(1);

                    let block_len = data.len() as u32;
                    peer.active_blocks
                        .remove(&(piece_index, block_offset, block_len));

                    // Only credit the peer if the block was useful
                    if !is_piece_done {
                        peer.bytes_downloaded_from_peer += len;
                        peer.bytes_downloaded_in_tick += len;
                        peer.total_bytes_downloaded += len;
                    }
                }

                effects.push(Effect::EmitManagerEvent(ManagerEvent::BlockReceived {
                    info_hash: self.info_hash.clone(),
                }));
                self.record_pending_file_activity(
                    piece_index,
                    block_offset,
                    data.len() as u32,
                    FileActivityDirection::Download,
                );

                if is_piece_done {
                    return effects;
                }

                if self.torrent_status == TorrentStatus::Validating {
                    return effects;
                }

                self.last_activity = TorrentActivity::DownloadingPiece(piece_index);

                let piece_size = self.get_piece_size(piece_index);

                if let Some(complete_data) =
                    self.piece_manager
                        .handle_block(piece_index, block_offset, &data, piece_size)
                {
                    // Mark as verifying
                    self.verifying_pieces.insert(piece_index);

                    if let Some(roots) = self.piece_to_roots.get(&piece_index) {
                        let piece_len = self
                            .torrent
                            .as_ref()
                            .map(|t| t.info.piece_length as u64)
                            .unwrap_or(0);
                        let global_offset = (piece_index as u64 * piece_len) + block_offset as u64;

                        let matching_root_info = roots
                            .iter()
                            .filter(|r| r.file_offset <= global_offset)
                            .max_by_key(|r| r.file_offset);

                        let (valid_length, relative_index, hashing_context_len) =
                            self.calculate_v2_verify_params(piece_index, complete_data.len());

                        if let Some(root_info) = matching_root_info {
                            if let Some(target_hash) = self.torrent.as_ref().and_then(|t| {
                                t.get_v2_hash_layer(
                                    piece_index,
                                    root_info.file_offset,
                                    root_info.length,
                                    1,
                                    &root_info.root_hash,
                                )
                            }) {
                                // SCENARIO: We have the piece-layer hash locally
                                effects.push(Effect::VerifyPieceV2 {
                                    peer_id: peer_id.clone(),
                                    piece_index,
                                    proof: Vec::new(),
                                    data: complete_data,
                                    root_hash: target_hash,
                                    _file_start_offset: root_info.file_offset,
                                    valid_length,
                                    relative_index,
                                    hashing_context_len,
                                });
                            } else if let Some(proof) = self.v2_proofs.get(&piece_index) {
                                // SCENARIO: We got a proof from the peer
                                effects.push(Effect::VerifyPieceV2 {
                                    peer_id: peer_id.clone(),
                                    piece_index,
                                    proof: proof.clone(),
                                    root_hash: root_info.root_hash.clone(),
                                    data: complete_data,
                                    _file_start_offset: root_info.file_offset,
                                    valid_length,
                                    relative_index,
                                    hashing_context_len,
                                });
                            } else if self
                                .torrent
                                .as_ref()
                                .is_some_and(|t| !t.info.pieces.is_empty())
                            {
                                // Fallback for Hybrid torrents
                                self.last_activity = TorrentActivity::VerifyingPiece(piece_index);
                                effects.push(Effect::VerifyPiece {
                                    peer_id: peer_id.clone(),
                                    piece_index,
                                    data: complete_data,
                                });
                            } else {
                                // Buffer v2 data and ask for proof.
                                self.v2_pending_data
                                    .insert(piece_index, (block_offset, complete_data));

                                let root_info_opt = self
                                    .piece_to_roots
                                    .get(&piece_index)
                                    .and_then(|roots| roots.first());

                                if let Some(r_info) = root_info_opt {
                                    let piece_len = self
                                        .torrent
                                        .as_ref()
                                        .map(|t| t.info.piece_length as u64)
                                        .unwrap_or(32768);
                                    let request_base = if piece_len >= 16384 {
                                        (piece_len / 16384).trailing_zeros()
                                    } else {
                                        0
                                    };

                                    let request_index = if piece_len >= 16384 {
                                        let global_piece_offset = piece_index as u64 * piece_len;
                                        let offset_in_file =
                                            global_piece_offset.saturating_sub(r_info.file_offset);
                                        let relative_block_index = offset_in_file / 16384;
                                        relative_block_index >> request_base
                                    } else {
                                        piece_index as u64
                                    };

                                    effects.push(Effect::RequestHashes {
                                        peer_id: peer_id.clone(),
                                        file_root: r_info.root_hash.clone(),
                                        piece_index: request_index as u32,
                                        length: 1,
                                        proof_layers: 0,
                                        base_layer: request_base,
                                    });
                                }
                            }
                        } else {
                            // Fallback attempt to V1 if possible
                            self.last_activity = TorrentActivity::VerifyingPiece(piece_index);
                            effects.push(Effect::VerifyPiece {
                                peer_id: peer_id.clone(),
                                piece_index,
                                data: complete_data,
                            });
                        }
                    } else {
                        self.last_activity = TorrentActivity::VerifyingPiece(piece_index);
                        effects.push(Effect::VerifyPiece {
                            peer_id: peer_id.clone(),
                            piece_index,
                            data: complete_data,
                        });
                    }
                }

                if let Some(peer) = self.peers.get(&peer_id) {
                    let low_water_mark = MAX_PIPELINE_DEPTH / 2;
                    if peer.inflight_requests <= low_water_mark {
                        effects.extend(self.update(Action::AssignWork {
                            peer_id: peer_id.clone(),
                        }));
                    }
                }

                effects
            }

            Action::MerkleProofReceived {
                peer_id,
                piece_index,
                proof,
            } => {
                if self.piece_manager.bitfield.get(piece_index as usize) == Some(&PieceStatus::Done)
                {
                    return vec![Effect::DoNothing];
                }

                if let Some((block_offset, data)) = self.v2_pending_data.remove(&piece_index) {
                    if let Some(roots) = self.piece_to_roots.get(&piece_index) {
                        let piece_len = self
                            .torrent
                            .as_ref()
                            .map(|t| t.info.piece_length as u64)
                            .unwrap_or(65536);

                        let global_offset = (piece_index as u64 * piece_len) + block_offset as u64;

                        let matching_root_info = roots
                            .iter()
                            .filter(|r| r.file_offset <= global_offset)
                            .max_by_key(|r| r.file_offset);

                        if let Some(root_info) = matching_root_info {
                            let (valid_length, _, hashing_context_len) =
                                self.calculate_v2_verify_params(piece_index, data.len());

                            let offset_in_file =
                                global_offset.saturating_sub(root_info.file_offset);
                            let actual_relative_index = (offset_in_file / piece_len) as u32;

                            let local_piece_hash = self.torrent.as_ref().and_then(|t| {
                                t.get_v2_hash_layer(
                                    actual_relative_index,
                                    root_info.file_offset,
                                    root_info.length,
                                    1,
                                    &root_info.root_hash,
                                )
                            });

                            let (verification_target, verification_proof) = if proof.len() == 32 {
                                (
                                    local_piece_hash.unwrap_or_else(|| proof.clone()),
                                    Vec::new(),
                                )
                            } else {
                                (root_info.root_hash.clone(), proof)
                            };

                            return vec![Effect::VerifyPieceV2 {
                                peer_id,
                                piece_index,
                                proof: verification_proof,
                                data,
                                root_hash: verification_target,
                                _file_start_offset: root_info.file_offset,
                                valid_length,
                                relative_index: actual_relative_index,
                                hashing_context_len,
                            }];
                        }
                    }
                }
                vec![Effect::DoNothing]
            }

            Action::PieceVerified {
                peer_id,
                piece_index,
                valid,
                data,
            } => {
                let mut effects = Vec::new();

                if piece_index as usize >= self.piece_manager.bitfield.len() {
                    return vec![Effect::DoNothing];
                }

                self.verifying_pieces.remove(&piece_index);
                self.v2_proofs.remove(&piece_index);
                self.v2_pending_data.remove(&piece_index);

                if valid {
                    if self.piece_manager.bitfield.get(piece_index as usize)
                        == Some(&PieceStatus::Done)
                    {
                        if let Some(peer) = self.peers.get_mut(&peer_id) {
                            peer.pending_requests.remove(&piece_index);
                        }

                        // Redundant piece; we already have it. Discard data and assign new work.
                        effects.extend(self.update(Action::AssignWork { peer_id }));
                    } else {
                        // Valid and needed piece. Request write to disk.
                        // The data payload is now properly passed from the Action.
                        effects.push(Effect::WriteToDisk {
                            peer_id: peer_id.clone(),
                            piece_index,
                            data,
                        });
                    }
                } else {
                    self.piece_manager.reset_piece_assembly(piece_index);
                    effects.push(Effect::DisconnectPeer { peer_id });
                }
                effects
            }

            Action::PieceWrittenToDisk {
                peer_id,
                piece_index,
            } => {
                if piece_index as usize >= self.piece_manager.bitfield.len() {
                    return vec![Effect::DoNothing];
                }

                if self.torrent_status == TorrentStatus::Validating
                    || self.torrent_status == TorrentStatus::AwaitingMetadata
                {
                    return vec![Effect::DoNothing];
                }

                let mut effects = Vec::new();

                if self.piece_manager.bitfield.get(piece_index as usize) == Some(&PieceStatus::Done)
                {
                    if let Some(peer) = self.peers.get_mut(&peer_id) {
                        peer.pending_requests.remove(&piece_index);
                    }
                    effects.extend(self.update(Action::AssignWork { peer_id }));
                    return effects;
                }

                // ACTUAL STATE CHANGE
                let peers_to_cancel = self.piece_manager.mark_as_complete(piece_index);

                effects.push(Effect::EmitManagerEvent(ManagerEvent::DiskWriteFinished));

                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    peer.pending_requests.remove(&piece_index);
                }

                effects.extend(self.update(Action::AssignWork {
                    peer_id: peer_id.clone(),
                }));

                for other_peer in peers_to_cancel {
                    if other_peer != peer_id {
                        if let Some(peer) = self.peers.get_mut(&other_peer) {
                            peer.pending_requests.remove(&piece_index);
                            // ... cancellation construction ...
                            let batch = self.piece_manager.cancel_tuples_for_piece(piece_index);
                            if !batch.is_empty() {
                                effects.push(Effect::SendToPeer {
                                    peer_id: other_peer.clone(),
                                    cmd: Box::new(TorrentCommand::BulkCancel(batch)),
                                });
                            }
                        }
                        effects.extend(self.update(Action::AssignWork {
                            peer_id: other_peer,
                        }));
                    }
                }

                effects.push(Effect::BroadcastHave { piece_index });
                effects.extend(self.update(Action::CheckCompletion));

                let all_peers: Vec<String> = self.peers.keys().cloned().collect();
                for pid in all_peers {
                    effects.extend(self.update(Action::AssignWork { peer_id: pid }));
                }

                effects
            }

            Action::PieceWriteFailed { piece_index } => {
                if piece_index as usize >= self.piece_manager.bitfield.len() {
                    return vec![Effect::DoNothing];
                }
                self.piece_manager.requeue_pending_to_need(piece_index);
                vec![Effect::EmitManagerEvent(ManagerEvent::DiskWriteFinished)]
            }

            Action::RequestUpload {
                peer_id,
                piece_index,
                block_offset,
                length,
            } => {
                if !self.data_available {
                    return vec![Effect::DoNothing];
                }

                if self.torrent.is_none() {
                    return vec![Effect::DoNothing];
                }

                if length > MAX_BLOCK_SIZE {
                    return vec![Effect::DoNothing];
                }

                self.last_activity = TorrentActivity::SendingPiece(piece_index);

                let mut allowed = false;
                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    if peer.am_choking == ChokeStatus::Unchoke
                        && self.piece_manager.bitfield.get(piece_index as usize)
                            == Some(&PieceStatus::Done)
                    {
                        allowed = true;
                    }
                }

                if allowed {
                    self.record_pending_file_activity(
                        piece_index,
                        block_offset,
                        length,
                        FileActivityDirection::Upload,
                    );
                    vec![Effect::ReadFromDisk {
                        peer_id,
                        block_info: BlockInfo {
                            piece_index,
                            offset: block_offset,
                            length,
                        },
                    }]
                } else {
                    vec![Effect::DoNothing]
                }
            }

            Action::TrackerResponse {
                url,
                peers,
                interval,
                min_interval,
            } => {
                let mut effects = Vec::new();

                if let Some(tracker) = self.trackers.get_mut(&url) {
                    let seeding_secs = if interval > 0 { interval + 1 } else { 1800 };
                    tracker.seeding_interval = Some(Duration::from_secs(seeding_secs));

                    let leeching_secs = min_interval.map(|m| m + 1).unwrap_or(60);
                    tracker.leeching_interval = Some(Duration::from_secs(leeching_secs));

                    let next_interval = if self.torrent_status != TorrentStatus::Done {
                        tracker.leeching_interval.unwrap()
                    } else {
                        tracker.seeding_interval.unwrap()
                    };
                    tracker.next_announce_time = self.now + next_interval;
                }

                for peer_addr in peers {
                    let peer_key = peer_addr.to_string();
                    if let Some((_, next_attempt)) = self.timed_out_peers.get(&peer_key) {
                        if self.now < *next_attempt {
                            continue;
                        }
                    }
                    effects.push(Effect::ConnectToPeer { addr: peer_addr });
                }

                effects
            }

            Action::TrackerError { url } => {
                if let Some(tracker) = self.trackers.get_mut(&url) {
                    let current_interval = if self.torrent_status != TorrentStatus::Done {
                        tracker.leeching_interval.unwrap_or(Duration::from_secs(60))
                    } else {
                        tracker
                            .seeding_interval
                            .unwrap_or(Duration::from_secs(1800))
                    };

                    let backoff = current_interval.mul_f32(2.0).min(Duration::from_secs(3600));
                    tracker.next_announce_time = self.now + backoff;
                }
                vec![Effect::DoNothing]
            }

            Action::PeerConnectionFailed { peer_addr } => {
                self.pending_failures.push(peer_addr);
                if self.pending_failures.len() >= 100 {
                    let effects = Vec::new();
                    let batch = std::mem::take(&mut self.pending_failures);
                    for addr in batch {
                        let (count, _) = self
                            .timed_out_peers
                            .get(&addr)
                            .cloned()
                            .unwrap_or((0, self.now));
                        let new_count = (count + 1).min(10);
                        let backoff_secs = (15 * 2u64.pow(new_count - 1)).min(1800);
                        self.timed_out_peers.insert(
                            addr,
                            (new_count, self.now + Duration::from_secs(backoff_secs)),
                        );
                    }
                    return effects;
                }
                vec![Effect::DoNothing]
            }

            Action::MetadataReceived {
                torrent,
                metadata_length,
            } => {
                if self.torrent.is_some() {
                    return vec![Effect::DoNothing];
                }

                self.torrent = Some(*torrent.clone());
                self.torrent_metadata_length = Some(metadata_length);

                let (v2_piece_count, piece_overrides) = self.rebuild_v2_mappings();

                let num_pieces = if !torrent.info.pieces.is_empty() {
                    torrent.info.pieces.len() / 20
                } else {
                    v2_piece_count as usize
                };

                self.piece_manager = PieceManager::new();
                self.piece_manager
                    .set_initial_fields(num_pieces, self.torrent_validation_status);

                let total_len: u64 = if torrent.info.meta_version == Some(2) {
                    (num_pieces as u64) * (torrent.info.piece_length as u64)
                } else if torrent.info.files.is_empty() {
                    torrent.info.length as u64
                } else {
                    torrent.info.files.iter().map(|f| f.length as u64).sum()
                };

                self.piece_manager.set_geometry(
                    torrent.info.piece_length as u32,
                    total_len,
                    piece_overrides,
                    self.torrent_validation_status,
                );
                if !self.file_priorities.is_empty() {
                    let priorities = self.calculate_piece_priorities(&self.file_priorities);
                    self.piece_manager.apply_priorities(priorities);
                }

                for peer in self.peers.values_mut() {
                    if peer.bitfield.len() > num_pieces {
                        peer.bitfield.truncate(num_pieces);
                    } else if peer.bitfield.len() < num_pieces {
                        peer.bitfield.resize(num_pieces, false);
                    }
                }

                let tracker_urls = normalize_tracker_urls(
                    self.trackers.keys().cloned().chain(torrent.tracker_urls()),
                );
                self.trackers = tracker_urls
                    .into_iter()
                    .map(|announce| {
                        let state = self.trackers.remove(&announce).unwrap_or(TrackerState {
                            next_announce_time: self.now,
                            leeching_interval: None,
                            seeding_interval: None,
                        });
                        (announce, state)
                    })
                    .collect();

                self.validation_pieces_found = 0;
                if self.torrent_data_path.is_some() {
                    self.rebuild_multi_file_info();
                    self.torrent_status = TorrentStatus::Validating;
                    return vec![Effect::StartValidation];
                }
                vec![Effect::DoNothing]
            }

            Action::ValidationComplete { completed_pieces } => {
                let mut effects = Vec::new();

                if self.torrent_status != TorrentStatus::Validating {
                    return vec![Effect::DoNothing];
                }

                for piece_index in &completed_pieces {
                    let _ = self.piece_manager.mark_as_complete(*piece_index);
                }

                self.torrent_status = TorrentStatus::Standard;

                self.piece_manager.pending_queue.clear();
                for peer in self.peers.values_mut() {
                    peer.pending_requests.clear();
                }
                self.piece_manager.clear_assembly_buffers();

                for status in self.piece_manager.bitfield.iter_mut() {
                    if *status != PieceStatus::Done {
                        *status = PieceStatus::Need;
                    }
                }

                // Rebuild Need Queue (now using all available pieces)
                self.piece_manager.need_queue.clear();
                for (index, status) in self.piece_manager.bitfield.iter().enumerate() {
                    let idx = index as u32;
                    if *status != PieceStatus::Done {
                        let is_skipped = !self.piece_manager.piece_priorities.is_empty()
                            && self.piece_manager.piece_priorities[index]
                                == EffectivePiecePriority::Skip;

                        if !is_skipped {
                            self.piece_manager.need_queue.push(idx);
                        }
                    }
                }

                if !self.is_paused {
                    if !self.has_started_announce_sent {
                        self.has_started_announce_sent = true;
                        effects.push(Effect::ConnectToPeersFromTrackers);
                    } else {
                        for url in self.trackers.keys() {
                            effects.push(Effect::AnnounceToTracker { url: url.clone() });
                        }
                    }
                }

                for piece_index in &completed_pieces {
                    effects.push(Effect::BroadcastHave {
                        piece_index: *piece_index,
                    });
                }

                effects.extend(self.update(Action::CheckCompletion));
                effects.extend(self.update(Action::RecalculateChokes {
                    random_seed: self.now.elapsed().as_nanos() as u64,
                }));

                for peer_id in self.peers.keys().cloned().collect::<Vec<_>>() {
                    effects.extend(self.update(Action::AssignWork { peer_id }));
                }

                effects
            }

            Action::CancelUpload {
                peer_id,
                piece_index,
                block_offset,
                length,
            } => {
                vec![Effect::AbortUpload {
                    peer_id,
                    block_info: BlockInfo {
                        piece_index,
                        offset: block_offset,
                        length,
                    },
                }]
            }

            Action::BlockSentToPeer {
                peer_id,
                byte_count,
            } => {
                self.session_total_uploaded =
                    self.session_total_uploaded.saturating_add(byte_count);
                self.bytes_uploaded_in_interval =
                    self.bytes_uploaded_in_interval.saturating_add(byte_count);

                if let Some(peer) = self.peers.get_mut(&peer_id) {
                    peer.bytes_uploaded_to_peer =
                        peer.bytes_uploaded_to_peer.saturating_add(byte_count);
                    peer.total_bytes_uploaded =
                        peer.total_bytes_uploaded.saturating_add(byte_count);
                    peer.bytes_uploaded_in_tick =
                        peer.bytes_uploaded_in_tick.saturating_add(byte_count);
                }

                vec![Effect::EmitManagerEvent(ManagerEvent::BlockSent {
                    info_hash: self.info_hash.clone(),
                })]
            }

            Action::Cleanup => {
                let mut effects = Vec::new();

                self.timed_out_peers
                    .retain(|_, (retry_count, _)| *retry_count < MAX_TIMEOUT_COUNT);

                let max_ram_usage = 1024 * 1024 * 1024; // 1 GB
                let piece_len = self
                    .torrent
                    .as_ref()
                    .map(|t| t.info.piece_length as usize)
                    .unwrap_or(16_384);
                let max_pending_items = max_ram_usage / piece_len;
                if self.v2_pending_data.len() > max_pending_items {
                    self.v2_pending_data.clear();
                }

                let mut stuck_peers = Vec::new();
                for (id, peer) in &self.peers {
                    if peer.peer_id.is_empty()
                        && self.now.saturating_duration_since(peer.created_at)
                            > Duration::from_secs(5)
                    {
                        stuck_peers.push(id.clone());
                    }
                }

                for peer_id in stuck_peers {
                    self.pending_disconnects.push(peer_id);
                }

                effects.extend(self.update(Action::PeerDisconnected {
                    peer_id: String::new(),
                    force: true,
                }));

                let am_seeding = !self.piece_manager.bitfield.is_empty()
                    && self
                        .piece_manager
                        .bitfield
                        .iter()
                        .all(|&s| s == PieceStatus::Done);

                if am_seeding && self.torrent_status != TorrentStatus::Done {
                    self.torrent_status = TorrentStatus::Done;
                    effects.extend(self.update(Action::CheckCompletion));
                }

                if am_seeding {
                    let mut peers_to_disconnect = Vec::new();
                    for (peer_id, peer) in &self.peers {
                        if !peer.bitfield.is_empty()
                            && peer.bitfield.iter().all(|&has_piece| has_piece)
                        {
                            peers_to_disconnect.push(peer_id.clone());
                        }
                    }
                    for peer_id in peers_to_disconnect {
                        effects.push(Effect::DisconnectPeer { peer_id });
                    }
                }

                effects
            }

            Action::Pause => {
                self.last_activity = TorrentActivity::Paused;
                self.is_paused = true;

                self.last_known_peers = self.peers.keys().cloned().collect();

                for (piece_index, _) in self.piece_manager.pending_queue.drain() {
                    self.piece_manager.need_queue.push(piece_index);
                }

                let mut peer_disconnects = Vec::new();
                let peer_ids: Vec<String> = self.peers.keys().cloned().collect();
                for peer_id in peer_ids {
                    if let Some(removed_peer) = self.peers.remove(&peer_id) {
                        for piece_index in removed_peer.pending_requests {
                            if self.piece_manager.bitfield.get(piece_index as usize)
                                != Some(&PieceStatus::Done)
                            {
                                self.piece_manager.requeue_pending_to_need(piece_index);
                            }
                        }

                        peer_disconnects.push(Effect::DisconnectPeerSession {
                            peer_id: peer_id.clone(),
                            peer_tx: removed_peer.peer_tx,
                        });
                        peer_disconnects.push(Effect::EmitManagerEvent(
                            ManagerEvent::PeerDisconnected {
                                info_hash: self.info_hash.clone(),
                            },
                        ));
                    }
                }

                self.number_of_successfully_connected_peers = self.peers.len();

                self.bytes_downloaded_in_interval = 0;
                self.bytes_uploaded_in_interval = 0;
                self.total_dl_prev_avg_ema = 0.0;
                self.total_ul_prev_avg_ema = 0.0;

                let mut effects = vec![
                    Effect::EmitMetrics {
                        bytes_dl: self.bytes_downloaded_in_interval,
                        bytes_ul: self.bytes_uploaded_in_interval,
                        file_activity_updates: self.drain_file_activity_updates(),
                    },
                    Effect::ClearAllUploads,
                ];
                effects.extend(peer_disconnects);
                effects
            }

            Action::Resume => {
                self.last_activity = TorrentActivity::ConnectingToPeers;
                self.is_paused = false;

                if self.torrent_status == TorrentStatus::Validating {
                    return vec![Effect::DoNothing];
                }

                let mut effects = vec![Effect::TriggerDhtSearch];

                effects.extend(self.update(Action::ConnectToWebSeeds));

                for (url, tracker) in self.trackers.iter_mut() {
                    tracker.next_announce_time = self.now + Duration::from_secs(60);
                    effects.push(Effect::AnnounceToTracker { url: url.clone() });
                }

                let peers_to_connect: Vec<String> = std::mem::take(&mut self.last_known_peers)
                    .into_iter()
                    .collect();
                for peer_addr in peers_to_connect {
                    if let Ok(addr) = peer_addr.parse::<SocketAddr>() {
                        effects.push(Effect::ConnectToPeer { addr });
                    }
                }

                effects
            }

            Action::Delete => {
                self.peers.clear();
                self.last_known_peers.clear();
                self.timed_out_peers.clear();

                self.v2_proofs.clear();
                self.v2_pending_data.clear();
                self.piece_to_roots.clear();
                self.verifying_pieces.clear();

                let num_pieces = self.piece_manager.bitfield.len();
                self.piece_manager = PieceManager::new();
                if num_pieces > 0 {
                    self.piece_manager.set_initial_fields(num_pieces, false);
                }
                self.piece_manager.pending_queue.clear();
                self.piece_manager.need_queue.clear();

                for status in self.piece_manager.bitfield.iter_mut() {
                    *status = PieceStatus::Need;
                }

                self.number_of_successfully_connected_peers = 0;

                self.session_total_downloaded = 0;
                self.session_total_uploaded = 0;

                // These must be cleared, otherwise they remain > 0 while total is 0
                self.bytes_downloaded_in_interval = 0;
                self.bytes_uploaded_in_interval = 0;

                self.is_paused = true;
                self.torrent_status = if self.torrent.is_some() {
                    TorrentStatus::Validating
                } else {
                    TorrentStatus::AwaitingMetadata
                };
                self.last_activity = TorrentActivity::Initializing;

                let mut effects = Vec::new();
                if let (Some(path), Some(mfi)) = (&self.torrent_data_path, &self.multi_file_info) {
                    let container = self.container_name.as_deref();
                    let (files, directories) = calculate_deletion_lists(mfi, path, container);
                    effects.push(Effect::DeleteFiles { files, directories });
                } else {
                    if self.torrent_status != TorrentStatus::AwaitingMetadata
                        && self.torrent_status != TorrentStatus::Validating
                    {
                        event!(
                            Level::WARN,
                            "Action::Delete triggered but torrent_data_path or mfi is missing."
                        );
                    } else {
                        event!(
                            Level::INFO,
                            "Aborting torrent before storage initialization."
                        );
                    }

                    effects.push(Effect::EmitManagerEvent(ManagerEvent::DeletionComplete(
                        self.info_hash.clone(),
                        Ok(()),
                    )));
                }
                effects
            }

            Action::UpdateListenPort => {
                let mut effects = Vec::new();

                for (url, tracker) in self.trackers.iter_mut() {
                    tracker.next_announce_time = self.now + Duration::from_secs(60);
                    effects.push(Effect::AnnounceToTracker { url: url.clone() });
                }

                effects
            }

            Action::SetUserTorrentConfig {
                torrent_data_path,
                file_priorities,
                container_name,
            } => {
                event!(
                    Level::INFO,
                    "Received User config {:?} - {} Priorities",
                    torrent_data_path,
                    file_priorities.len()
                );

                self.torrent_data_path = Some(torrent_data_path);
                self.file_priorities = file_priorities;
                self.container_name = container_name;

                if self.torrent.is_some() {
                    let priorities = self.calculate_piece_priorities(&self.file_priorities);
                    self.piece_manager.apply_priorities(priorities);
                }

                let mut effects = Vec::new();

                if self.torrent.is_some() && self.multi_file_info.is_none() {
                    self.rebuild_multi_file_info();

                    if self.multi_file_info.is_some() {
                        self.torrent_status = TorrentStatus::Validating;
                        effects.push(Effect::StartValidation);
                    }
                }

                effects.extend(self.update(Action::CheckCompletion));

                effects
            }

            Action::SetDataAvailability { available } => {
                self.data_available = available;
                self.update(Action::RecalculateChokes { random_seed: 0 })
            }

            Action::ValidationProgress { count } => {
                self.validation_pieces_found = count;
                vec![Effect::DoNothing]
            }

            Action::Shutdown => {
                self.is_paused = true;
                let left = if let Some(t) = &self.torrent {
                    let completed = self
                        .piece_manager
                        .bitfield
                        .iter()
                        .filter(|&&s| s == PieceStatus::Done)
                        .count();

                    let total_len = if t.info.files.is_empty() {
                        t.info.length
                    } else {
                        t.info.files.iter().map(|f| f.length).sum()
                    };

                    (total_len as usize).saturating_sub(completed * t.info.piece_length as usize)
                } else {
                    0
                };

                let tracker_urls: Vec<String> = self.trackers.keys().cloned().collect();
                let uploaded = self.session_total_uploaded as usize;
                let downloaded = self.session_total_downloaded as usize;

                self.peers.clear();

                vec![Effect::PrepareShutdown {
                    tracker_urls,
                    left,
                    uploaded,
                    downloaded,
                }]
            }

            Action::FatalError => self.update(Action::Pause),
        }
    }

    fn rebuild_v2_mappings(&mut self) -> (u32, HashMap<u32, u32>) {
        let mut overrides = HashMap::new();
        let mut v2_piece_count: u32 = 0;

        if let Some(torrent) = &self.torrent {
            let mapping = torrent.calculate_v2_mapping();
            self.piece_to_roots = mapping.piece_to_roots;
            v2_piece_count = mapping.piece_count as u32;

            if torrent.info.meta_version == Some(2) {
                let piece_len = torrent.info.piece_length as u64;
                let mut v2_roots = torrent.get_v2_roots();
                v2_roots.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));

                let mut current_idx = 0;
                for (_, length, _) in v2_roots {
                    if length > 0 && piece_len > 0 {
                        let file_pieces = length.div_ceil(piece_len);
                        let tail_len = (length % piece_len) as u32;
                        if tail_len > 0 {
                            let tail_idx = (current_idx + file_pieces - 1) as u32;
                            overrides.insert(tail_idx, tail_len);
                        }
                        current_idx += file_pieces;
                    }
                }
            }
        }
        (v2_piece_count, overrides)
    }

    fn calculate_v2_verify_params(&self, piece_index: u32, data_len: usize) -> (usize, u32, usize) {
        if let Some(roots) = self.piece_to_roots.get(&piece_index) {
            if let Some(root_info) = roots.first() {
                let piece_len = self
                    .torrent
                    .as_ref()
                    .map(|t| t.info.piece_length as u64)
                    .unwrap_or(0);

                let piece_start_global = piece_index as u64 * piece_len;
                let offset_in_file = piece_start_global.saturating_sub(root_info.file_offset);
                let remaining = root_info.length.saturating_sub(offset_in_file);

                let valid_length = std::cmp::min(data_len as u64, remaining) as usize;
                let relative_index = (offset_in_file / piece_len) as u32;

                let hashing_context_len = if root_info.length <= piece_len {
                    root_info.length as usize
                } else {
                    piece_len as usize
                };

                return (valid_length, relative_index, hashing_context_len);
            }
        }
        (data_len, 0, data_len)
    }

    fn record_pending_file_activity(
        &mut self,
        piece_index: u32,
        block_offset: u32,
        length: u32,
        direction: FileActivityDirection,
    ) {
        let piece_length = match self
            .torrent
            .as_ref()
            .map(|torrent| torrent.info.piece_length as u64)
        {
            Some(piece_length) if length > 0 && piece_length > 0 => piece_length,
            _ => return,
        };

        let start = (piece_index as u64)
            .saturating_mul(piece_length)
            .saturating_add(block_offset as u64);
        let end = start.saturating_add(length as u64);
        if end <= start {
            return;
        }

        let pending = match direction {
            FileActivityDirection::Download => &mut self.pending_download_file_activity,
            FileActivityDirection::Upload => &mut self.pending_upload_file_activity,
        };

        if let Some(last) = pending.last_mut() {
            if start >= last.start && start <= last.end {
                last.end = last.end.max(end);
                return;
            }
        }

        pending.push(FileActivityInterval { start, end });
    }

    fn drain_file_activity_updates(&mut self) -> Vec<FileActivityUpdate> {
        let mut updates = Vec::with_capacity(2);
        let effective_root = match &self.container_name {
            Some(name) if !name.is_empty() => {
                self.torrent_data_path.as_ref().map(|path| path.join(name))
            }
            _ => self.torrent_data_path.clone(),
        };
        let Some(multi_file_info) = self.multi_file_info.as_ref() else {
            self.pending_download_file_activity.clear();
            self.pending_upload_file_activity.clear();
            return updates;
        };

        let drain_direction = |intervals: &mut Vec<FileActivityInterval>,
                               direction: FileActivityDirection| {
            if intervals.is_empty() {
                return None;
            }

            intervals.sort_unstable_by_key(|interval| interval.start);

            let mut write_idx = 0usize;
            for read_idx in 1..intervals.len() {
                if intervals[read_idx].start <= intervals[write_idx].end {
                    intervals[write_idx].end =
                        intervals[write_idx].end.max(intervals[read_idx].end);
                } else {
                    write_idx += 1;
                    intervals[write_idx] = intervals[read_idx];
                }
            }
            intervals.truncate(write_idx + 1);

            let mut touched_paths = Vec::new();
            let mut interval_idx = 0usize;

            for file_info in &multi_file_info.files {
                let file_start = file_info.global_start_offset;
                let file_end = file_start.saturating_add(file_info.length);

                while interval_idx < intervals.len() && intervals[interval_idx].end <= file_start {
                    interval_idx += 1;
                }

                if interval_idx == intervals.len() {
                    break;
                }

                let mut candidate_idx = interval_idx;
                let mut touches_file = false;
                while candidate_idx < intervals.len() {
                    let interval = intervals[candidate_idx];
                    if interval.start >= file_end {
                        break;
                    }
                    if interval.end > file_start && interval.start < file_end {
                        touches_file = true;
                        break;
                    }
                    candidate_idx += 1;
                }

                if touches_file {
                    touched_paths.push(
                        effective_root
                            .as_ref()
                            .and_then(|root| {
                                file_info.path.strip_prefix(root).ok().map(|relative| {
                                    relative
                                        .iter()
                                        .map(|part| part.to_string_lossy().into_owned())
                                        .collect::<Vec<_>>()
                                        .join("/")
                                })
                            })
                            .unwrap_or_else(|| {
                                file_info
                                    .path
                                    .file_name()
                                    .map(|name| name.to_string_lossy().into_owned())
                                    .unwrap_or_else(|| {
                                        file_info.path.to_string_lossy().into_owned()
                                    })
                            }),
                    );
                }
            }

            (!touched_paths.is_empty()).then_some(FileActivityUpdate {
                touched_relative_paths: touched_paths,
                direction,
            })
        };

        let mut downloads = std::mem::take(&mut self.pending_download_file_activity);
        if let Some(update) = drain_direction(&mut downloads, FileActivityDirection::Download) {
            updates.push(update);
        }

        let mut uploads = std::mem::take(&mut self.pending_upload_file_activity);
        if let Some(update) = drain_direction(&mut uploads, FileActivityDirection::Upload) {
            updates.push(update);
        }

        updates
    }

    pub fn rebuild_multi_file_info(&mut self) {
        // Guard 1: Ensure metadata exists
        let torrent = match &self.torrent {
            Some(t) => t,
            None => {
                event!(
                    Level::DEBUG,
                    "rebuild_multi_file_info: Skipping. No torrent metadata available."
                );
                return;
            }
        };

        // Guard 2: Handle the Option<PathBuf>
        let path = match &self.torrent_data_path {
            Some(p) if !p.as_os_str().is_empty() => p,
            Some(_) => {
                event!(Level::WARN,
                    torrent_name = %torrent.info.name,
                    "rebuild_multi_file_info: torrent_data_path is Some, but the path is empty."
                );
                return;
            }
            None => {
                event!(Level::WARN,
                    torrent_name = %torrent.info.name,
                    "rebuild_multi_file_info: torrent_data_path is None."
                );
                return;
            }
        };

        let effective_path = match &self.container_name {
            // Case A: User specified a folder
            Some(name) if !name.is_empty() => path.join(name),

            // Case B: User explicitly said "No Folder" (Empty String)
            Some(_) => path.clone(),

            // Case C: Auto/Default (None) -> Intelligent Behavior
            None => {
                let is_multi_file = !torrent.info.files.is_empty();
                // BitTorrent standard: multi-file torrents use folders
                if is_multi_file {
                    let info_hash_hex = hex::encode(&self.info_hash);
                    let unique_name = format!("{} [{}]", torrent.info.name, info_hash_hex);
                    self.container_name = Some(unique_name.clone());
                    path.join(unique_name)
                } else {
                    path.clone()
                }
            }
        };
        self.multi_file_info = MultiFileInfo::new(
            &effective_path,
            &torrent.info.name,
            if torrent.info.files.is_empty() { None } else { Some(&torrent.info.files) },
            if torrent.info.files.is_empty() { Some(torrent.info.length as u64) } else { None },
            &self.file_priorities,
        ).map_err(|e| {
            event!(Level::ERROR, error = %e, "rebuild_multi_file_info: Failed to create MultiFileInfo");
            e
        }).ok();

        if self.multi_file_info.is_some() {
            event!(Level::INFO,
                torrent_name = %torrent.info.name,
                "rebuild_multi_file_info: Storage successfully initialized in state."
            );
        }
    }

    fn calculate_piece_priorities(
        &self,
        new_file_priorities: &HashMap<usize, FilePriority>,
    ) -> Vec<EffectivePiecePriority> {
        let torrent = match &self.torrent {
            Some(t) => t,
            None => return Vec::new(),
        };

        let num_pieces = self.piece_manager.bitfield.len();
        if num_pieces == 0 {
            return Vec::new();
        }

        let mut piece_vec = vec![EffectivePiecePriority::Normal; num_pieces];
        let piece_len = torrent.info.piece_length as u64;

        // Default all to Skip, then paint Normal/High over them.
        piece_vec.fill(EffectivePiecePriority::Skip);

        let mut file_start = 0u64;

        let files_iter = if !torrent.info.files.is_empty() {
            torrent
                .info
                .files
                .iter()
                .map(|f| f.length)
                .enumerate()
                .collect::<Vec<_>>()
        } else {
            vec![(0, torrent.info.length)]
        };

        for (file_idx, length) in files_iter {
            let file_end = file_start + (length as u64);
            let start_piece = (file_start / piece_len) as usize;
            let end_piece = ((file_end.saturating_sub(1)) / piece_len) as usize;

            let priority = new_file_priorities
                .get(&file_idx)
                .unwrap_or(&FilePriority::Normal);

            for (p_idx, piece) in piece_vec
                .iter_mut()
                .enumerate()
                .take(end_piece + 1)
                .skip(start_piece)
            {
                if p_idx >= num_pieces {
                    break;
                }

                match priority {
                    FilePriority::High => {
                        *piece = EffectivePiecePriority::High;
                    }
                    FilePriority::Normal | FilePriority::Mixed => {
                        if *piece != EffectivePiecePriority::High {
                            *piece = EffectivePiecePriority::Normal;
                        }
                    }
                    FilePriority::Skip => {
                        // Stays Skip unless overwritten by another file
                    }
                }
            }
            file_start = file_end;
        }
        piece_vec
    }
}

impl TorrentState {
    fn refresh_peer_admission_guard(&mut self) {
        let reopen_threshold = (PEER_ADMISSION_QUALITY_THRESHOLD * 50) / 100;
        let connected = self.number_of_successfully_connected_peers;

        if self.accepting_new_peers {
            if connected >= PEER_ADMISSION_QUALITY_THRESHOLD {
                self.accepting_new_peers = false;
            }
        } else if connected <= reopen_threshold {
            self.accepting_new_peers = true;
        }
    }
}

pub fn calculate_deletion_lists(
    mfi: &MultiFileInfo,
    base_path: &Path,
    known_container_name: Option<&str>,
) -> (Vec<PathBuf>, Vec<PathBuf>) {
    let mut files = Vec::new();
    let mut dirs_to_delete = HashSet::new();

    for file_info in &mfi.files {
        files.push(file_info.path.clone());

        // Walk up the directory tree
        let mut current = file_info.path.parent();
        while let Some(dir) = current {
            if dir == base_path {
                break;
            }
            if dir.starts_with(base_path) {
                dirs_to_delete.insert(dir.to_path_buf());
            } else {
                break;
            }
            current = dir.parent();
        }
    }

    // STRICT SAFETY: Only delete the base_path if we explicitly recorded a container name
    // and the current base_path's folder name matches it.
    if let Some(recorded_name) = known_container_name {
        if let Some(folder_name) = base_path.file_name().and_then(|n| n.to_str()) {
            if folder_name == recorded_name {
                dirs_to_delete.insert(base_path.to_path_buf());
            }
        }
    }

    let mut sorted_dirs: Vec<PathBuf> = dirs_to_delete.into_iter().collect();
    sorted_dirs.sort_by_key(|b| std::cmp::Reverse(b.as_os_str().len()));

    (files, sorted_dirs)
}

#[derive(Debug, Clone)]
pub struct PeerState {
    pub ip_port: String,
    pub peer_id: Vec<u8>,
    pub bitfield: Vec<bool>,
    pub am_choking: ChokeStatus,
    pub peer_choking: ChokeStatus,
    pub peer_tx: Sender<TorrentCommand>,
    pub am_interested: bool,
    pub pending_requests: HashSet<u32>,
    pub peer_is_interested_in_us: bool,
    pub bytes_downloaded_from_peer: u64,
    pub bytes_uploaded_to_peer: u64,
    pub bytes_downloaded_in_tick: u64,
    pub bytes_uploaded_in_tick: u64,
    pub prev_avg_dl_ema: f64,
    pub prev_avg_ul_ema: f64,
    pub total_bytes_downloaded: u64,
    pub total_bytes_uploaded: u64,
    pub download_speed_bps: u64,
    pub upload_speed_bps: u64,
    pub upload_slots_semaphore: Arc<Semaphore>,
    pub last_action: TorrentCommand,
    pub action_counts: HashMap<Discriminant<TorrentCommand>, u64>,
    pub created_at: Instant,
    pub inflight_requests: usize,
    pub active_blocks: HashSet<(u32, u32, u32)>,
}

impl PeerState {
    pub fn new(ip_port: String, peer_tx: Sender<TorrentCommand>, created_at: Instant) -> Self {
        Self {
            ip_port,
            peer_id: Vec::new(),
            bitfield: Vec::new(),
            am_choking: ChokeStatus::Choke,
            peer_choking: ChokeStatus::Choke,
            peer_tx,
            am_interested: false,
            pending_requests: HashSet::new(),
            peer_is_interested_in_us: false,
            bytes_downloaded_from_peer: 0,
            bytes_uploaded_to_peer: 0,
            bytes_downloaded_in_tick: 0,
            bytes_uploaded_in_tick: 0,
            total_bytes_downloaded: 0,
            total_bytes_uploaded: 0,
            prev_avg_dl_ema: 0.0,
            prev_avg_ul_ema: 0.0,
            download_speed_bps: 0,
            upload_speed_bps: 0,
            upload_slots_semaphore: Arc::new(Semaphore::new(PEER_UPLOAD_IN_FLIGHT_LIMIT)),
            last_action: TorrentCommand::SuccessfullyConnected(String::new()),
            action_counts: HashMap::new(),
            created_at,
            inflight_requests: 0,
            active_blocks: HashSet::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::command::TorrentCommand;
    use crate::torrent_file::V2RootInfo;
    use crate::torrent_manager::piece_manager::PieceManager;
    use tokio::sync::mpsc;

    // --- Test Helpers ---

    pub(crate) fn create_empty_state() -> TorrentState {
        TorrentState {
            info_hash: vec![0; 20],
            peers: HashMap::new(),
            piece_manager: PieceManager::new(),
            trackers: HashMap::new(),
            torrent_data_path: Some(PathBuf::from("/tmp/superseedr_test")),
            ..Default::default()
        }
    }

    pub(crate) fn create_dummy_torrent(piece_count: usize) -> Torrent {
        // Construct a minimal Torrent struct for testing
        // Note: You might need to adjust this based on your actual Torrent struct visibility
        use crate::torrent_file::Info;

        Torrent {
            announce: Some("http://tracker.test".to_string()),
            announce_list: None,
            url_list: None,
            info: Info {
                name: "test_torrent".to_string(),
                piece_length: 16384,                 // 16KB
                pieces: vec![0u8; 20 * piece_count], // 20 bytes per piece hash
                length: (16384 * piece_count) as i64,
                files: vec![],
                private: None,
                md5sum: None,
                meta_version: None,
                file_tree: None,
            },
            info_dict_bencode: vec![],
            created_by: None,
            creation_date: None,
            encoding: None,
            comment: None,
            piece_layers: None,
        }
    }

    fn add_peer(state: &mut TorrentState, id: &str) {
        let (tx, _) = mpsc::channel(1);
        let mut peer = PeerState::new(id.to_string(), tx, state.now);
        // Assume peer has handshake
        peer.peer_id = id.as_bytes().to_vec();
        state.peers.insert(id.to_string(), peer);
    }

    fn drained_download_paths_for_activity(
        state: &mut TorrentState,
        piece_index: u32,
        block_offset: u32,
        length: u32,
    ) -> Vec<String> {
        state.record_pending_file_activity(
            piece_index,
            block_offset,
            length,
            FileActivityDirection::Download,
        );

        state
            .drain_file_activity_updates()
            .into_iter()
            .find(|update| update.direction == FileActivityDirection::Download)
            .map(|update| update.touched_relative_paths)
            .unwrap_or_default()
    }

    #[test]
    fn test_peer_admission_guard_closes_under_high_connected_pressure() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = true;

        for i in 0..PEER_ADMISSION_QUALITY_THRESHOLD {
            add_peer(&mut state, &format!("peer_{}", i));
        }
        state.number_of_successfully_connected_peers = state.peers.len();

        let _ = state.update(Action::Tick { dt_ms: 1000 });

        assert!(
            !state.accepting_new_peers,
            "expected admission guard to close under heavy connected-peer pressure"
        );
    }

    #[test]
    fn test_peer_admission_guard_reopens_at_reopen_threshold() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = false;

        let reopen_threshold = (PEER_ADMISSION_QUALITY_THRESHOLD * 50) / 100;
        for i in 0..reopen_threshold {
            add_peer(&mut state, &format!("peer_{}", i));
        }
        state.number_of_successfully_connected_peers = state.peers.len();

        let _ = state.update(Action::Tick { dt_ms: 1000 });

        assert!(
            state.accepting_new_peers,
            "expected admission guard to reopen at configured reopen threshold"
        );
    }

    #[test]
    fn test_peer_admission_guard_closes_immediately_on_successful_connection() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = true;

        for i in 0..PEER_ADMISSION_QUALITY_THRESHOLD {
            add_peer(&mut state, &format!("peer_{}", i));
        }

        let _ = state.update(Action::PeerSuccessfullyConnected {
            peer_id: "peer_0".to_string(),
        });

        assert!(
            !state.accepting_new_peers,
            "expected admission guard to close immediately when threshold is reached"
        );
    }

    #[test]
    fn test_peer_admission_guard_closes_immediately_on_peer_discovery() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = true;

        for i in 0..PEER_ADMISSION_QUALITY_THRESHOLD {
            let (tx, _rx) = mpsc::channel(1);
            let _ = state.update(Action::RegisterPeer {
                peer_id: format!("peer_{}", i),
                tx,
            });
        }

        assert!(
            !state.accepting_new_peers,
            "expected admission guard to close immediately when discovery reaches threshold"
        );
    }

    #[test]
    fn test_peer_admission_guard_stays_closed_above_reopen_threshold() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = false;

        let reopen_threshold = (PEER_ADMISSION_QUALITY_THRESHOLD * 50) / 100;
        for i in 0..(reopen_threshold + 1) {
            add_peer(&mut state, &format!("peer_{}", i));
        }
        state.number_of_successfully_connected_peers = state.peers.len();

        let _ = state.update(Action::Tick { dt_ms: 1000 });

        assert!(
            !state.accepting_new_peers,
            "guard should remain closed while connected count is above reopen threshold"
        );
    }

    #[test]
    fn test_peer_admission_guard_reopens_at_exact_reopen_threshold() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        state.accepting_new_peers = false;

        let reopen_threshold = (PEER_ADMISSION_QUALITY_THRESHOLD * 50) / 100;
        for i in 0..reopen_threshold {
            add_peer(&mut state, &format!("peer_{}", i));
        }
        state.number_of_successfully_connected_peers = state.peers.len();

        let _ = state.update(Action::Tick { dt_ms: 1000 });

        assert!(
            state.accepting_new_peers,
            "guard should reopen when connected count reaches the exact reopen threshold"
        );
    }

    // --- SCENARIO 1: Initialization ---

    #[test]
    fn test_metadata_received_triggers_initialization_flow() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/tmp")); // Set a path for MFI rebuild
        let torrent = create_dummy_torrent(5);

        let action = Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 123,
        };
        let effects = state.update(action);

        assert_eq!(state.torrent_status, TorrentStatus::Validating);
        assert!(state.torrent.is_some());

        // Check internal state instead of Effect::InitializeStorage
        assert!(
            state.multi_file_info.is_some(),
            "MFI should be initialized internally"
        );

        // The first effect is now StartValidation
        assert!(matches!(effects[0], Effect::StartValidation));
    }

    // --- SCENARIO 2: Choking Logic (Leeching) ---

    #[test]
    fn test_recalculate_chokes_unchokes_fastest_downloader() {
        // GIVEN: A state in Leeching mode (Standard) with 5 interested peers competing for 4 slots.
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard; // Leeching

        // Peers will be ranked by bytes_downloaded_from_peer (contribution).

        add_peer(&mut state, "slow_peer");
        let slow_peer = state.peers.get_mut("slow_peer").unwrap();
        slow_peer.peer_is_interested_in_us = true;
        slow_peer.bytes_downloaded_from_peer = 10; // Low contribution (Must lose)
        slow_peer.am_choking = ChokeStatus::Unchoke; // Start unchoked to test transition

        add_peer(&mut state, "fast_peer");
        let fast_peer = state.peers.get_mut("fast_peer").unwrap();
        fast_peer.peer_is_interested_in_us = true;
        fast_peer.bytes_downloaded_from_peer = 10_000; // High contribution (Must win)

        // Their contribution must be between the Fast Peer (10,000) and the Slow Peer (10).
        for i in 1..=3 {
            let id = format!("med_peer_{}", i);
            add_peer(&mut state, &id);
            let peer = state.peers.get_mut(&id).unwrap();
            peer.peer_is_interested_in_us = true;
            peer.bytes_downloaded_from_peer = 100; // Intermediate contribution
        }

        // WHEN: We recalculate chokes. The top 4 (Fast + 3 Med) should be unchoked.
        let effects = state.update(Action::RecalculateChokes { random_seed: 0 });

        // THEN: Fast peer is Unchoked, Slow peer is Choked (due to competition)
        let fast_peer_state = state.peers.get("fast_peer").unwrap();
        let slow_peer_state = state.peers.get("slow_peer").unwrap();

        // Assertion 1: The fastest peer must be Unchoked.
        assert_eq!(fast_peer_state.am_choking, ChokeStatus::Unchoke);

        // Assertion 2: The slowest peer must be Choked. (This satisfies the original test intent.)
        assert_eq!(slow_peer_state.am_choking, ChokeStatus::Choke);

        // Assertion 3: Check effects for the slow peer's transition (optional, but good practice)
        let sent_choke = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { peer_id, cmd }
        if peer_id == "slow_peer" && matches!(**cmd, TorrentCommand::PeerChoke))
        });
        assert!(sent_choke, "Should send Choke to slow peer");

        // Assertion 4: Verify the total number of unchoked peers is 4 (UPLOAD_SLOTS_DEFAULT).
        let unchoked_count = state
            .peers
            .values()
            .filter(|p| p.am_choking == ChokeStatus::Unchoke)
            .count();
        assert_eq!(
            unchoked_count,
            super::UPLOAD_SLOTS_DEFAULT,
            "Total unchoked count should be exactly 4."
        );
    }

    // --- SCENARIO 3: Choking Logic (Seeding) ---

    #[test]
    fn test_recalculate_chokes_unchokes_fastest_uploader_when_seeding() {
        // GIVEN: A state that is DONE (Seeding) with 5 interested peers competing for 4 slots.
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Done;

        add_peer(&mut state, "slow_leecher");
        let slow_leecher = state.peers.get_mut("slow_leecher").unwrap();
        slow_leecher.peer_is_interested_in_us = true;
        slow_leecher.bytes_uploaded_to_peer = 1_000; // Low upload volume (Must lose)
        slow_leecher.am_choking = ChokeStatus::Unchoke; // Start unchoked to test transition

        add_peer(&mut state, "fast_leecher");
        let fast_leecher = state.peers.get_mut("fast_leecher").unwrap();
        fast_leecher.peer_is_interested_in_us = true;
        fast_leecher.bytes_uploaded_to_peer = 50_000; // High upload volume (Must win)

        // Their uploaded bytes must be between the Fast Peer (50,000) and the Slow Peer (1,000).
        for i in 1..=3 {
            let id = format!("med_leecher_{}", i);
            add_peer(&mut state, &id);
            let peer = state.peers.get_mut(&id).unwrap();
            peer.peer_is_interested_in_us = true;
            peer.bytes_uploaded_to_peer = 10_000; // Intermediate volume
            peer.am_choking = ChokeStatus::Choke;
        }

        // WHEN: Recalculate chokes. The top 4 (Fast + 3 Med) should be unchoked.
        let _ = state.update(Action::RecalculateChokes { random_seed: 0 });

        // THEN:
        // Assertion 1: The fastest uploader must be Unchoked.
        assert_eq!(state.peers["fast_leecher"].am_choking, ChokeStatus::Unchoke);

        // Assertion 2: The slowest peer must be Choked. (This satisfies the test intent.)
        assert_eq!(state.peers["slow_leecher"].am_choking, ChokeStatus::Choke);

        // Assertion 3: Verify the total number of unchoked peers is 4 (UPLOAD_SLOTS_DEFAULT).
        let unchoked_count = state
            .peers
            .values()
            .filter(|p| p.am_choking == ChokeStatus::Unchoke)
            .count();
        assert_eq!(
            unchoked_count,
            super::UPLOAD_SLOTS_DEFAULT,
            "Total unchoked count should be exactly 4."
        );
    }

    // --- SCENARIO 4: Work Assignment ---
    #[test]
    fn test_assign_work_requests_piece_peer_has() {
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(10);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(10, false);
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.block_manager.set_geometry(
            16384,
            163840,
            vec![],
            vec![],
            HashMap::new(),
            false,
        ); // NEW: Init geometry

        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![false; 10];
        peer.bitfield[0] = true;
        state.piece_manager.need_queue.push(0);

        let effects = state.update(Action::AssignWork {
            peer_id: "peer_A".to_string(),
        });

        // NEW ASSERTION: Check for BulkRequest
        let request = effects.iter().find_map(|e| match e {
            Effect::SendToPeer { cmd, .. } => match **cmd {
                TorrentCommand::BulkRequest(ref requests) => {
                    requests.first().map(|(index, _, _)| *index)
                }
                _ => None,
            },
            _ => None,
        });

        assert_eq!(request, Some(0), "Should request piece 0 from peer_A");
    }

    #[test]
    fn test_data_unavailable_blocks_unchoke_and_upload() {
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(1);
        state.torrent = Some(torrent);
        state.torrent_status = TorrentStatus::Standard;
        state.data_available = false;
        state.piece_manager.set_initial_fields(1, false);
        state.piece_manager.bitfield[0] = PieceStatus::Done;

        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.peer_is_interested_in_us = true;
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.am_choking = ChokeStatus::Choke;

        let choke_effects = state.update(Action::RecalculateChokes { random_seed: 0 });
        assert!(matches!(choke_effects.as_slice(), [Effect::DoNothing]));
        assert_eq!(state.peers["peer_A"].am_choking, ChokeStatus::Choke);

        let upload_effects = state.update(Action::RequestUpload {
            peer_id: "peer_A".to_string(),
            piece_index: 0,
            block_offset: 0,
            length: 16_384,
        });
        assert!(matches!(upload_effects.as_slice(), [Effect::DoNothing]));
    }

    #[test]
    fn test_set_data_availability_does_not_emit_metrics() {
        let mut state = create_empty_state();

        let effects = state.update(Action::SetDataAvailability { available: false });

        assert!(!state.data_available);
        assert!(matches!(effects.as_slice(), [Effect::DoNothing]));
    }

    #[test]
    fn test_set_data_availability_rechokes_existing_upload_slots() {
        let mut state = create_empty_state();
        state.torrent = Some(create_dummy_torrent(1));
        state.torrent_status = TorrentStatus::Done;

        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.peer_is_interested_in_us = true;
        peer.am_choking = ChokeStatus::Unchoke;

        let effects = state.update(Action::SetDataAvailability { available: false });

        assert!(!state.data_available);
        assert_eq!(state.peers["peer_A"].am_choking, ChokeStatus::Choke);
        assert!(effects.iter().any(|effect| {
            matches!(effect, Effect::SendToPeer { peer_id, cmd }
                if peer_id == "peer_A" && matches!(**cmd, TorrentCommand::PeerChoke))
        }));
    }

    // --- SCENARIO 5: Piece Verification Success ---

    #[test]
    fn test_piece_verified_valid_trigger_write() {
        // GIVEN: State waiting for verification of piece 1
        let mut state = create_empty_state();
        state.piece_manager.set_initial_fields(5, false);
        // Mark piece 1 as needed/pending in piece manager context
        // (Assuming default state allows this transition)

        let data = vec![1, 2, 3, 4];

        // WHEN: Piece 1 is verified successfully
        let effects = state.update(Action::PieceVerified {
            peer_id: "peer_1".into(),
            piece_index: 1,
            valid: true,
            data: data.clone(),
        });

        // THEN: Effect::WriteToDisk is emitted
        let write_effect = effects
            .iter()
            .find(|e| matches!(e, Effect::WriteToDisk { piece_index: 1, .. }));
        assert!(write_effect.is_some());
    }

    #[test]
    fn test_piece_verified_invalid_disconnects_peer() {
        // GIVEN: State
        let mut state = create_empty_state();
        state.piece_manager.set_initial_fields(5, false);

        // WHEN: Piece 1 fails verification
        let effects = state.update(Action::PieceVerified {
            peer_id: "bad_peer".into(),
            piece_index: 1,
            valid: false,
            data: vec![],
        });

        // THEN: Peer is disconnected
        let disconnect = effects
            .iter()
            .any(|e| matches!(e, Effect::DisconnectPeer { peer_id } if peer_id == "bad_peer"));
        assert!(disconnect);
    }

    // --- SCENARIO 6: Completion ---

    #[test]
    fn test_check_completion_transitions_to_done() {
        // GIVEN: All pieces are marked as Done
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(3);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(3, false);

        state.torrent_status = TorrentStatus::Standard;

        state.trackers.insert(
            "http://tracker".into(),
            TrackerState {
                next_announce_time: Instant::now(),
                leeching_interval: None,
                seeding_interval: None,
            },
        );

        // Manually mark all pieces as Done (simulating write success)
        for i in 0..3 {
            state.piece_manager.bitfield[i] = PieceStatus::Done;
        }

        // WHEN: CheckCompletion is called
        let effects = state.update(Action::CheckCompletion);

        // THEN: Status becomes Done, AnnounceCompleted emitted
        assert_eq!(state.torrent_status, TorrentStatus::Done);

        let announce_completed = effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceCompleted { .. }));
        assert!(announce_completed);
    }

    // --- SCENARIO 7: Cleanup / Disconnect ---

    #[test]
    fn test_peer_disconnect_decrements_count() {
        // GIVEN: A connected peer
        let mut state = create_empty_state();
        add_peer(&mut state, "peer_X");
        state.number_of_successfully_connected_peers = 1;

        // WHEN: Peer disconnects
        let effects = state.update(Action::PeerDisconnected {
            peer_id: "peer_X".to_string(),
            force: true,
        });

        // THEN: Peer removed, count decremented, Disconnect effect emitted
        assert!(!state.peers.contains_key("peer_X"));
        assert_eq!(state.number_of_successfully_connected_peers, 0);

        assert!(effects
            .iter()
            .any(|e| matches!(e, Effect::DisconnectPeer { .. })));
        assert!(effects.iter().any(|e| matches!(
            e,
            Effect::EmitManagerEvent(ManagerEvent::PeerDisconnected { .. })
        )));
    }

    #[test]
    fn test_enter_endgame_mode() {
        // GIVEN: A torrent with 2 pieces, 1 already pending
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(2);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            16384,
            16384 * 2,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.bitfield = vec![true, true];
        peer.peer_choking = ChokeStatus::Unchoke;

        // Piece 0 is already pending (assigned to someone else, theoretically)
        state.piece_manager.mark_as_pending(0, "other_peer".into());

        // Only Piece 1 is left in need_queue
        state.piece_manager.need_queue.clear();
        state.piece_manager.need_queue.push(1);

        // WHEN: We assign the LAST needed piece to peer_A
        state.update(Action::AssignWork {
            peer_id: "peer_A".into(),
        });

        // THEN:

        assert!(state.piece_manager.need_queue.is_empty());

        assert_eq!(state.torrent_status, TorrentStatus::Endgame);
    }

    #[test]
    fn test_peer_chokes_us_mid_download() {
        // GIVEN: Peer A is unchoked and we have pending requests
        let mut state = create_empty_state();
        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.pending_requests.insert(5); // We asked for piece 5

        // WHEN: Peer A chokes us
        let _ = state.update(Action::PeerChoked {
            peer_id: "peer_A".into(),
        });

        // THEN:

        assert_eq!(state.peers["peer_A"].peer_choking, ChokeStatus::Choke);

        // (Strict clients cancel immediately; lenient ones wait. Verify YOUR logic here.)
    }

    #[test]
    fn test_optimistic_unchoke_rotates() {
        // GIVEN: 6 peers competing for 4 slots (UPLOAD_SLOTS_DEFAULT = 4).
        let mut state = create_empty_state();

        for i in 1..=4 {
            let id = format!("fast_A{}", i);
            add_peer(&mut state, &id);
            let p = state.peers.get_mut(&id).unwrap();
            p.peer_is_interested_in_us = true;
            p.bytes_downloaded_from_peer = 1000;
        }

        add_peer(&mut state, "optimistic_B");
        let opt_peer = state.peers.get_mut("optimistic_B").unwrap();
        opt_peer.peer_is_interested_in_us = true;
        opt_peer.bytes_downloaded_from_peer = 100;

        add_peer(&mut state, "slow_C");
        let slow_peer = state.peers.get_mut("slow_C").unwrap();
        slow_peer.peer_is_interested_in_us = true;
        slow_peer.bytes_downloaded_from_peer = 10;

        // Force timer expiration and set fixed seed for deterministic rotation
        state.optimistic_unchoke_timer =
            Some(state.now.checked_sub(Duration::from_secs(31)).unwrap());

        // WHEN: Recalculate Chokes
        let _ = state.update(Action::RecalculateChokes {
            // Use a fixed seed (0) to ensure the rotation selects the same peer (optimistic_B)
            // from the pool of losers (B and C).
            random_seed: 0,
        });

        // THEN:

        let unchoked_count = state
            .peers
            .values()
            .filter(|p| p.am_choking == ChokeStatus::Unchoke)
            .count();

        let expected_count = super::UPLOAD_SLOTS_DEFAULT + 1;
        assert_eq!(
            unchoked_count, expected_count,
            "Total unchoked count mismatch. Expected 5 (4+1)."
        );

        assert_eq!(state.peers["fast_A1"].am_choking, ChokeStatus::Unchoke);

        assert_eq!(state.peers["optimistic_B"].am_choking, ChokeStatus::Unchoke);

        assert_eq!(state.peers["slow_C"].am_choking, ChokeStatus::Choke);
    }

    #[test]
    fn test_peer_have_updates_bitfield_and_triggers_work() {
        // GIVEN: Peer A connected with empty bitfield
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(10);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(10, false);

        state.torrent_status = TorrentStatus::Standard;

        add_peer(&mut state, "peer_A");
        state.peers.get_mut("peer_A").unwrap().bitfield = vec![false; 10];

        // We need piece 5
        // Note: If need_queue is a VecDeque, use .push_back(5) instead of .push(5)
        state.piece_manager.need_queue.push(5);

        // WHEN: Peer sends "Have(5)"
        let effects = state.update(Action::PeerHavePiece {
            peer_id: "peer_A".into(),
            piece_index: 5,
        });

        // THEN:

        assert!(state.peers["peer_A"].bitfield[5]);

        let interest = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { cmd, .. }
        if matches!(**cmd, TorrentCommand::ClientInterested))
        });

        assert!(interest, "Should send Interested message");
    }

    #[test]
    fn test_cancel_upload_aborts_task() {
        // GIVEN: We are seeding
        let mut state = create_empty_state();
        add_peer(&mut state, "leecher");

        // WHEN: Peer cancels request for piece 0, block 0
        let effects = state.update(Action::CancelUpload {
            peer_id: "leecher".into(),
            piece_index: 0,
            block_offset: 0,
            length: 16384,
        });

        // THEN: Effect::AbortUpload is emitted
        let abort = effects.iter().any(|e| {
            matches!(e, Effect::AbortUpload { peer_id, block_info }
        if peer_id == "leecher" && block_info.piece_index == 0)
        });

        assert!(abort);
    }

    #[test]
    fn test_invariant_pending_removed_on_disk_write() {
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(20);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(20, false);
        state.piece_manager.block_manager.set_geometry(
            16384,
            16384 * 20,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        add_peer(&mut state, "peer_A");
        let peer = state.peers.get_mut("peer_A").unwrap();
        peer.bitfield = vec![true; 20]; // Peer has everything
        peer.peer_choking = ChokeStatus::Unchoke;

        // We need piece 0
        state.piece_manager.need_queue.push(0);

        // This moves Piece 0 from Need -> Pending and adds to Peer's pending_requests
        state.update(Action::AssignWork {
            peer_id: "peer_A".into(),
        });

        // VERIFY SETUP: Piece 0 must be pending now
        assert!(
            state.peers["peer_A"].pending_requests.contains(&0),
            "Setup failed: Piece 0 should be pending"
        );

        state.update(Action::PieceWrittenToDisk {
            peer_id: "peer_A".into(),
            piece_index: 0,
        });

        // If the code is correct, piece 0 is removed from the peer.
        // If sabotaged, piece 0 remains, and this assert will panic.
        let is_still_pending = state.peers["peer_A"].pending_requests.contains(&0);

        assert!(!is_still_pending,
            "INVARIANT VIOLATION: Piece 0 is marked DONE globally, but still exists in peer_A's pending_requests!");

        // Double check global status is actually done (to ensure test validity)
        assert_eq!(state.piece_manager.bitfield[0], PieceStatus::Done);
    }

    #[test]
    fn regression_delete_clears_piece_manager_state() {
        // BUG CONTEXT: Previously, Action::Delete cleared queues but left 'partial blocks'
        // inside PieceManager. When a new peer connected and sent data for that piece,
        // PieceManager panicked with "subtract with overflow" because it compared
        // new offsets against old, stale buffer state.

        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(5);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(5, false);
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.need_queue = vec![0];

        add_peer(&mut state, "peer_A");
        let _ = state.update(Action::PeerUnchoked {
            peer_id: "peer_A".into(),
        });
        let _ = state.update(Action::PeerHavePiece {
            peer_id: "peer_A".into(),
            piece_index: 0,
        });
        let _ = state.update(Action::AssignWork {
            peer_id: "peer_A".into(),
        });

        let data = vec![1; 100];
        let _ = state.update(Action::IncomingBlock {
            peer_id: "peer_A".into(),
            piece_index: 0,
            block_offset: 0,
            data: data.clone(),
        });

        let _ = state.update(Action::Delete);

        // If state wasn't wiped, this causes "subtract with overflow" or "ghost queue" panic
        add_peer(&mut state, "peer_B");

        // We must reset status to Standard manually as Delete sets it to Validating
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.need_queue = vec![0];

        let _ = state.update(Action::PeerUnchoked {
            peer_id: "peer_B".into(),
        });
        let _ = state.update(Action::PeerHavePiece {
            peer_id: "peer_B".into(),
            piece_index: 0,
        });

        // CRITICAL STEP: Sending data for the same piece index as before.
        // If the old partial buffer exists, this crashes.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut s = state; // Move state in
            s.update(Action::IncomingBlock {
                peer_id: "peer_B".into(),
                piece_index: 0,
                block_offset: 0,
                data,
            });
        }));

        assert!(
            result.is_ok(),
            "Regression: Action::Delete failed to wipe PieceManager state!"
        );
    }

    #[test]
    fn regression_redundant_disk_write_completion() {
        // BUG CONTEXT: The fuzzer found that if 'PieceWrittenToDisk' fires twice
        // (race condition), the PieceManager would panic trying to mark a 'Done' piece as done.

        let mut state = create_empty_state();

        // FIX: Explicitly set status to Standard.
        // Otherwise, the new safety guard in PieceWrittenToDisk ignores the action.
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.set_initial_fields(1, false);
        add_peer(&mut state, "peer_A");
        state
            .peers
            .get_mut("peer_A")
            .unwrap()
            .pending_requests
            .insert(0);

        state.update(Action::PieceWrittenToDisk {
            peer_id: "peer_A".into(),
            piece_index: 0,
        });

        assert_eq!(state.piece_manager.bitfield[0], PieceStatus::Done);

        // Should be ignored gracefully, not panic.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut s = state;
            s.update(Action::PieceWrittenToDisk {
                peer_id: "peer_A".into(),
                piece_index: 0,
            });
        }));

        assert!(
            result.is_ok(),
            "Regression: Double PieceWrittenToDisk caused a panic!"
        );
    }

    #[test]
    fn regression_metric_integer_overflow() {
        // BUG CONTEXT: Sending huge byte counts caused u64 overflow panics.
        let mut state = create_empty_state();
        add_peer(&mut state, "peer_A");

        let huge_val = u64::MAX - 100;

        state.update(Action::BlockSentToPeer {
            peer_id: "peer_A".into(),
            byte_count: huge_val,
        });

        state.update(Action::BlockSentToPeer {
            peer_id: "peer_A".into(),
            byte_count: 200,
        });

        assert_eq!(state.session_total_uploaded, u64::MAX);
        assert_eq!(state.peers["peer_A"].total_bytes_uploaded, u64::MAX);
    }

    #[test]
    fn regression_peer_count_sync() {
        let mut state = create_empty_state();
        let peer_id = "peer_A".to_string();

        super::tests::add_peer(&mut state, &peer_id);
        state.update(Action::PeerSuccessfullyConnected {
            peer_id: peer_id.clone(),
        });
        assert_eq!(
            state.number_of_successfully_connected_peers, 1,
            "Counter after first connection"
        );

        state.update(Action::PeerSuccessfullyConnected {
            peer_id: peer_id.clone(),
        });
        assert_eq!(
            state.number_of_successfully_connected_peers, 1,
            "Counter on duplicate connection"
        );

        state.update(Action::PeerDisconnected {
            peer_id: peer_id.clone(),
            force: true,
        });
        assert_eq!(
            state.number_of_successfully_connected_peers, 0,
            "Counter after disconnection"
        );
    }

    #[test]
    fn test_download_starts_immediately_after_validation() {
        // GIVEN: A torrent with 2 pieces (so we don't hit Endgame immediately)
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(2); // <--- Changed to 2
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false); // <--- Changed to 2
        state.piece_manager.block_manager.set_geometry(
            16384,
            163840,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Validating;

        // We need piece 0 and 1
        state.piece_manager.need_queue = vec![0, 1];

        add_peer(&mut state, "seeder");

        // 0x80 is binary 10000000 -> 1st bit set -> Piece 0 available
        state.update(Action::PeerBitfieldReceived {
            peer_id: "seeder".into(),
            bitfield: vec![0x80],
        });

        state.update(Action::PeerUnchoked {
            peer_id: "seeder".into(),
        });

        // Pre-check
        assert!(state.peers["seeder"].pending_requests.is_empty());

        // WHEN: Validation completes
        let effects = state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });

        println!("{:?}", effects);

        // THEN:

        assert_eq!(state.torrent_status, TorrentStatus::Standard);

        let request_sent = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { cmd, .. }
            if matches!(**cmd, TorrentCommand::BulkRequest(ref reqs) if !reqs.is_empty() && reqs[0].0 == 0))
        });

        assert!(
            request_sent,
            "Regression: Validation finished but download did not trigger!"
        );

        assert!(state.peers["seeder"].inflight_requests == 1);
    }

    #[test]
    fn test_assign_work_sends_interested_even_if_unchoked() {
        // GIVEN: A standard torrent state where we need Piece 0
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(1);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state.piece_manager.block_manager.set_geometry(
            16384,
            163840,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        // We explicitly need Piece 0
        state.piece_manager.need_queue = vec![0];

        // GIVEN: A connected peer ("generous_seeder")
        add_peer(&mut state, "generous_seeder");
        let peer = state.peers.get_mut("generous_seeder").unwrap();

        // CRITICAL SETUP FOR BUG REPRODUCTION:

        peer.bitfield = vec![true];

        peer.peer_choking = ChokeStatus::Unchoke;

        peer.am_interested = false;

        // WHEN: We assign work
        let effects = state.update(Action::AssignWork {
            peer_id: "generous_seeder".to_string(),
        });

        // THEN: We MUST send 'ClientInterested' BEFORE requesting data.

        // Check for Interested message
        let sent_interested = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { cmd, .. }
            if matches!(**cmd, TorrentCommand::ClientInterested))
        });

        // Check for Request message
        let sent_request = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { cmd, .. }
            if matches!(**cmd, TorrentCommand::BulkRequest(ref reqs) if !reqs.is_empty() && reqs[0].0 == 0))
        });

        // ASSERTIONS
        // If the bug is present, `sent_interested` will be false, but `sent_request` will be true.
        assert!(sent_interested, "PROTOCOL VIOLATION: Failed to send 'Interested' message because peer was already unchoked.");
        assert!(
            sent_request,
            "Should immediately request blocks because peer is unchoked."
        );

        // Verify internal state update
        assert!(
            state.peers["generous_seeder"].am_interested,
            "Internal state 'am_interested' was not updated to true."
        );
    }

    #[test]
    fn test_partial_piece_request() {
        // ... (Keep Setup Code) ...
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 32768; // 2 blocks per piece
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.block_manager.set_geometry(
            32768,
            65536,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );

        state.piece_manager.need_queue = vec![0, 1];

        add_peer(&mut state, "target_peer");
        let target = state.peers.get_mut("target_peer").unwrap();
        target.peer_choking = ChokeStatus::Unchoke;
        target.bitfield = vec![true, true];
        target.am_interested = true;

        // Simulate receiving FIRST BLOCK of Piece 0
        let data = vec![0u8; 16384];

        let effects = state.update(Action::IncomingBlock {
            peer_id: "target_peer".into(),
            piece_index: 0,
            block_offset: 0,
            data,
        });

        // REMOVED: The second manual AssignWork call which was returning empty effects.

        // Verify we ask for the SECOND block
        let requested_params = effects.iter().find_map(|e| {
            if let Effect::SendToPeer { cmd, .. } = e {
                if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                    if let Some((index, begin, length)) = reqs.first() {
                        return Some((*index, *begin, *length));
                    }
                }
            }
            None
        });

        if let Some((idx, begin, length)) = requested_params {
            assert_eq!(idx, 0, "Should pick Piece 0");
            assert_eq!(begin, 16384, "Should resume at offset 16384");
            assert_eq!(length, 16384, "Should request 1 block");
        } else {
            panic!("No request sent for partial piece");
        }
    }

    #[test]
    fn test_assign_work_non_aligned_boundary_piece_identity() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        assert!(
            !requests.is_empty(),
            "Expected at least one boundary request"
        );
        assert!(
            requests.iter().all(|(idx, _, _)| *idx == 1),
            "All requests must target piece 1, got {:?}",
            requests
        );
    }

    #[test]
    fn test_assign_work_non_aligned_boundary_offsets_for_piece() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        let mut piece_1_offsets: Vec<(u32, u32)> = requests
            .iter()
            .filter(|(idx, _, _)| *idx == 1)
            .map(|(_, begin, len)| (*begin, *len))
            .collect();
        piece_1_offsets.sort_unstable();

        assert_eq!(
            piece_1_offsets,
            vec![(0, 16_384), (16_384, 3_616)],
            "Piece-1 requests must follow piece-local geometry exactly"
        );
    }

    #[test]
    fn test_incoming_block_non_aligned_updates_correct_piece_assembler() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        let mut saw_verify_piece_1 = false;
        for (piece_index, block_offset, length) in requests {
            let effects = state.update(Action::IncomingBlock {
                peer_id: "target_peer".to_string(),
                piece_index,
                block_offset,
                data: vec![0u8; length as usize],
            });
            saw_verify_piece_1 |= effects
                .iter()
                .any(|e| matches!(e, Effect::VerifyPiece { piece_index: 1, .. }));
        }

        assert!(
            !state
                .piece_manager
                .block_manager
                .legacy_buffers
                .contains_key(&0),
            "Assembler for piece 0 should remain untouched while downloading piece 1"
        );
        // Piece 1 may either still be buffering or already have emitted verification and cleared buffer.
        let piece_1_buffering = state
            .piece_manager
            .block_manager
            .legacy_buffers
            .contains_key(&1);
        assert!(
            piece_1_buffering || saw_verify_piece_1,
            "Piece 1 must either buffer in its own assembler or reach verification"
        );
    }

    #[test]
    fn test_restart_resume_non_aligned_requests_only_missing_blocks() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        // Receive one valid piece-1 block before "restart".
        let _ = state.update(Action::IncomingBlock {
            peer_id: "target_peer".to_string(),
            piece_index: 1,
            block_offset: 0,
            data: vec![0u8; 16_384],
        });

        // Simulate restart: session-level inflight/active state should be cleared.
        if let Some(peer_after_restart) = state.peers.get_mut("target_peer") {
            peer_after_restart.inflight_requests = 0;
            peer_after_restart.active_blocks.clear();
        }

        // Re-assign after restart.
        let effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        assert_eq!(
            requests,
            vec![(1, 16_384, 3_616)],
            "Resume must request only the remaining piece-1 boundary block"
        );
    }

    #[test]
    fn test_non_aligned_verify_fail_requeue_clears_exact_piece_state() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.mark_as_complete(0);
        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());

        let _ = state.update(Action::PieceVerified {
            peer_id: "target_peer".to_string(),
            piece_index: 1,
            valid: false,
            data: vec![],
        });

        assert!(
            state.piece_manager.bitfield.first() == Some(&PieceStatus::Done),
            "Piece 0 completion state must remain unchanged"
        );
        assert!(
            state.piece_manager.bitfield.get(1) == Some(&PieceStatus::Need),
            "Piece 1 must be requeued and incomplete after verification failure"
        );
    }

    #[test]
    fn test_assign_work_non_aligned_no_zero_or_oversize_block_requests() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        assert!(!requests.is_empty(), "Expected request batch");
        for (piece_index, begin, len) in requests {
            assert!(len > 0, "Zero-length request is invalid");
            assert_eq!(
                piece_index, 1,
                "Boundary request must remain in target piece namespace"
            );
            assert!(
                begin + len <= 20_000,
                "Request exceeds piece boundary: begin={} len={}",
                begin,
                len
            );
        }
    }

    #[test]
    fn test_non_aligned_full_piece_download_emits_verify_for_target_piece() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "target_peer");
        let peer = state.peers.get_mut("target_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "target_peer".to_string());
        peer.pending_requests.insert(1);

        let mut effects = state.update(Action::AssignWork {
            peer_id: "target_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        for (piece_index, block_offset, length) in requests {
            effects = state.update(Action::IncomingBlock {
                peer_id: "target_peer".to_string(),
                piece_index,
                block_offset,
                data: vec![0u8; length as usize],
            });
        }

        let verify_piece_1 = effects
            .iter()
            .any(|e| matches!(e, Effect::VerifyPiece { piece_index: 1, .. }));
        assert!(
            verify_piece_1,
            "Completing target non-aligned piece should emit VerifyPiece for piece 1"
        );
    }

    #[test]
    fn test_assign_work_tiny_piece_keeps_target_piece_identity() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 1_024;
        torrent.info.length = 2_048;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            1_024,
            2_048,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "tiny_peer");
        let peer = state.peers.get_mut("tiny_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "tiny_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "tiny_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        assert_eq!(
            requests,
            vec![(1, 0, 1_024)],
            "Tiny-piece request should stay in piece-local namespace"
        );
    }

    #[test]
    fn test_multi_file_non_aligned_priority_boundary_mixed_piece_not_skipped() {
        let mut state = create_empty_state();
        let piece_len = 20_000;

        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = piece_len;
        torrent.info.length = 40_000;
        torrent.info.files = vec![
            crate::torrent_file::InfoFile {
                length: 18_000, // Entirely in piece 0
                path: vec!["A.bin".into()],
                md5sum: None,
                attr: None,
            },
            crate::torrent_file::InfoFile {
                length: 22_000, // Crosses piece boundary into piece 1
                path: vec!["B.bin".into()],
                md5sum: None,
                attr: None,
            },
        ];
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);

        let mut priorities = HashMap::new();
        priorities.insert(0, FilePriority::Skip); // Skip file A only.

        let p = state.calculate_piece_priorities(&priorities);

        assert_eq!(
            p[0],
            EffectivePiecePriority::Normal,
            "Piece 0 spans skipped and non-skipped files and must not be skipped"
        );
        assert_eq!(
            p[1],
            EffectivePiecePriority::Normal,
            "Piece 1 belongs to non-skipped file and must remain normal"
        );
    }

    #[test]
    fn test_non_aligned_choke_disconnect_requeues_without_ghost_pending() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        add_peer(&mut state, "race_peer");
        let peer = state.peers.get_mut("race_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.pending_requests.insert(1);
        state
            .piece_manager
            .mark_as_pending(1, "race_peer".to_string());

        let _ = state.update(Action::PeerChoked {
            peer_id: "race_peer".to_string(),
        });
        let _ = state.update(Action::PeerDisconnected {
            peer_id: "race_peer".to_string(),
            force: true,
        });

        assert!(
            !state.piece_manager.pending_queue.contains_key(&1),
            "Pending queue should be cleared for disconnected/choked peer"
        );
        assert!(
            state.piece_manager.need_queue.contains(&1),
            "Piece must be requeued after choke/disconnect race"
        );
        assert!(
            !state.peers.contains_key("race_peer"),
            "Peer should be removed after disconnect"
        );
    }

    #[test]
    fn test_non_aligned_assign_work_not_suppressed_by_previous_piece_global_bits() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 20_000;
        torrent.info.length = 40_000;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.block_manager.set_geometry(
            20_000,
            40_000,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        // Mark piece 0 as complete first. On non-aligned geometry this sets a shared
        // global boundary block bit that must not suppress piece-1 requests.
        state.piece_manager.mark_as_complete(0);

        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        add_peer(&mut state, "boundary_peer");
        let peer = state.peers.get_mut("boundary_peer").unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true, true];
        peer.am_interested = true;

        state
            .piece_manager
            .mark_as_pending(1, "boundary_peer".to_string());
        peer.pending_requests.insert(1);

        let effects = state.update(Action::AssignWork {
            peer_id: "boundary_peer".to_string(),
        });

        let requests: Vec<(u32, u32, u32)> = effects
            .iter()
            .filter_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(reqs) = &**cmd {
                        return Some(reqs.clone());
                    }
                }
                None
            })
            .flatten()
            .collect();

        let mut piece_1_offsets: Vec<(u32, u32)> = requests
            .iter()
            .filter(|(idx, _, _)| *idx == 1)
            .map(|(_, begin, len)| (*begin, *len))
            .collect();
        piece_1_offsets.sort_unstable();

        assert_eq!(
            piece_1_offsets,
            vec![(0, 16_384), (16_384, 3_616)],
            "Piece-1 requests must not be suppressed by piece-0 global block bits"
        );
    }

    #[test]
    fn test_upload_starts_immediately_after_validation() {
        // GIVEN: A state set up to require upload activity after validation.
        let mut state = create_empty_state();

        // Setup a 2-piece torrent.
        let torrent = create_dummy_torrent(2);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);
        state.torrent_status = TorrentStatus::Validating; // Initial state

        add_peer(&mut state, "leecher");
        let leecher = state.peers.get_mut("leecher").unwrap();
        // Manager is initially choking the peer (am_choking == Choke)
        leecher.peer_is_interested_in_us = true;

        // We update the piece manager to simulate pieces 0 and 1 being present on disk.
        // The bitfield status should still be in the initial state here.

        // WHEN: Validation completes, finding pieces 0 and 1 on disk.
        let effects = state.update(Action::ValidationComplete {
            completed_pieces: vec![0, 1],
        });

        // THEN:

        assert_eq!(
            state.torrent_status,
            TorrentStatus::Done,
            "Torrent status should be DONE after finding all pieces."
        );

        let unchoke_sent = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { peer_id, cmd }
        if peer_id == "leecher" && matches!(**cmd, TorrentCommand::PeerUnchoke))
        });

        assert!(
            unchoke_sent,
            "Validation completion failed to trigger Unchoke for interested peer."
        );

        assert_eq!(state.peers["leecher"].am_choking, ChokeStatus::Unchoke);

        let have_broadcasted = effects
            .iter()
            .any(|e| matches!(e, Effect::BroadcastHave { piece_index: 0 }));
        assert!(
            have_broadcasted,
            "Validation completion failed to trigger BroadcastHave."
        );
    }

    #[test]
    fn test_tracker_spam_during_validation() {
        // GIVEN: A torrent that has metadata and is currently validating.
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(100); // Simulate a large torrent that takes time
        state.torrent = Some(torrent);
        state.torrent_status = TorrentStatus::Validating; // CRITICAL: Status is Validating

        // Setup a tracker state where the initial announce time has passed (time = now).
        let tracker_url = "http://tracker.test".to_string();
        state.trackers.insert(
            tracker_url.clone(),
            TrackerState {
                next_announce_time: state.now, // Ready to announce immediately
                leeching_interval: Some(Duration::from_secs(60)),
                seeding_interval: None,
            },
        );

        // CRITICAL ACTION: Advance time by 1ms (ensures the timer check is hit).
        let _ = state.update(Action::Tick { dt_ms: 1 });

        // Reset next_announce_time to ensure it's still available (not strictly necessary but defensive)
        state
            .trackers
            .get_mut(&tracker_url)
            .unwrap()
            .next_announce_time = state.now;

        // WHEN: Action::Tick is executed again while still validating.
        let effects = state.update(Action::Tick { dt_ms: 1 });

        // THEN: The torrent should have generated NO tracker announce effects because validation blocks periodic activity.
        let announce_sent = effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceToTracker { .. }));

        assert!(!announce_sent, "FAILURE: Tracker announce was sent during the validation phase, indicating the system is inefficiently spamming the tracker while busy.");
    }

    #[test]
    fn metadata_received_renormalizes_existing_trackers_and_keeps_http_fallback() {
        let mut state = create_empty_state();
        state.trackers.insert(
            "http://tracker.local:6969/announce".to_string(),
            TrackerState {
                next_announce_time: state.now,
                leeching_interval: Some(Duration::from_secs(60)),
                seeding_interval: None,
            },
        );

        let mut torrent = create_dummy_torrent(4);
        torrent.announce = Some("udp://tracker.local:6969/announce".to_string());
        torrent.announce_list = Some(vec![vec!["https://tracker-alt.local/announce".to_string()]]);

        let _ = state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 0,
        });

        let mut tracker_urls: Vec<_> = state.trackers.keys().cloned().collect();
        tracker_urls.sort();
        assert_eq!(
            tracker_urls,
            vec![
                "http://tracker.local:6969/announce".to_string(),
                "https://tracker-alt.local/announce".to_string(),
                "udp://tracker.local:6969/announce".to_string(),
            ]
        );
    }

    // In src/torrent_manager/state.rs, inside mod tests { ... }

    #[test]
    fn test_manager_init_active_triggers_announce() {
        // GIVEN: A clean state with one tracker configured.
        let mut state = create_empty_state();
        let tracker_url = "http://test.tracker".to_string();
        state.trackers.insert(
            tracker_url.clone(),
            TrackerState {
                next_announce_time: state.now,
                leeching_interval: None,
                seeding_interval: None,
            },
        );

        // WHEN: The manager initializes in the active state.
        let effects = state.update(Action::TorrentManagerInit {
            is_paused: false,
            announce_immediately: true,
        });

        // THEN:

        let announce_sent = effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceToTracker { url } if url == &tracker_url));
        assert!(announce_sent, "Should trigger AnnounceToTracker.");

        assert!(!state.is_paused);
    }

    // In src/torrent_manager/state.rs, inside mod tests { ... }

    #[test]
    fn test_manager_init_paused_halts_activity() {
        // GIVEN: A clean state with one tracker configured.
        let mut state = create_empty_state();
        let tracker_url = "http://test.tracker".to_string();
        state.trackers.insert(
            tracker_url.clone(),
            TrackerState {
                next_announce_time: state.now,
                leeching_interval: None,
                seeding_interval: None,
            },
        );

        // WHEN: The manager initializes in the paused state.
        let effects = state.update(Action::TorrentManagerInit {
            is_paused: true,
            announce_immediately: false,
        });

        // THEN:

        assert!(state.is_paused);

        let network_activity = effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceToTracker { .. }));
        assert!(
            !network_activity,
            "No network activity should be generated when starting paused."
        );
    }

    #[test]
    fn test_pause_disconnects_live_peers_and_clears_state() {
        let mut state = create_empty_state();
        let (peer_a_tx, _peer_a_rx) = mpsc::channel(1);
        let (peer_b_tx, _peer_b_rx) = mpsc::channel(1);

        state.update(Action::RegisterPeer {
            peer_id: "127.0.0.1:4101".into(),
            tx: peer_a_tx,
        });
        state.update(Action::RegisterPeer {
            peer_id: "127.0.0.1:4102".into(),
            tx: peer_b_tx,
        });

        let effects = state.update(Action::Pause);

        assert!(state.is_paused);
        assert!(
            state.peers.is_empty(),
            "pause should clear peer state immediately"
        );

        let disconnect_count = effects
            .iter()
            .filter(|effect| matches!(effect, Effect::DisconnectPeerSession { .. }))
            .count();
        assert_eq!(
            disconnect_count, 2,
            "pause should disconnect every live peer"
        );
    }

    #[test]
    fn test_state_scale_2k_blocks_simulation() {
        let num_pieces = 2000;
        let piece_len = 16_384;

        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(num_pieces);

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.block_manager.set_geometry(
            piece_len as u32,
            (piece_len * num_pieces) as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        let peer_id = "worker_peer".to_string();
        add_peer(&mut state, &peer_id);

        // Setup Peer
        let bitfield = vec![0xFF; num_pieces.div_ceil(8)];
        state.update(Action::PeerBitfieldReceived {
            peer_id: peer_id.clone(),
            bitfield,
        });

        // Initialize queue early to capture setup effects
        let mut pending_actions = std::collections::VecDeque::new();

        // FIX: Capture initial requests from Unchoke logic
        let initial_effects = state.update(Action::PeerUnchoked {
            peer_id: peer_id.clone(),
        });
        for effect in initial_effects {
            if let Effect::SendToPeer { cmd, .. } = effect {
                if let TorrentCommand::BulkRequest(requests) = *cmd {
                    for (index, begin, length) in requests {
                        let data = vec![0u8; length as usize];
                        pending_actions.push_back(Action::IncomingBlock {
                            peer_id: peer_id.clone(),
                            piece_index: index,
                            block_offset: begin,
                            data,
                        });
                    }
                }
            }
        }

        state
            .piece_manager
            .update_rarity(state.peers.values().map(|p| &p.bitfield));

        // --- 2. SIMULATION LOOP ---
        let mut pieces_completed = 0;
        let mut loop_count = 0;

        println!("Starting State Simulation: 20,000 Blocks...");
        let start = std::time::Instant::now();

        while pieces_completed < num_pieces {
            loop_count += 1;
            if loop_count > 300_000 {
                // Trace dump on failure
                let peer = state.peers.get(&peer_id).unwrap();
                println!("\n!!! STALL DETECTED !!!");
                println!("Loop Count: {}", loop_count);
                println!("Pieces Completed: {}", pieces_completed);
                println!("Need Queue: {}", state.piece_manager.need_queue.len());
                println!("Pending Queue: {}", state.piece_manager.pending_queue.len());
                println!("Peer Inflight (State): {}", peer.inflight_requests);
                println!("Pending Actions Queue: {}", pending_actions.len());
                panic!("Infinite loop detected! Pipeline stalled.");
            }

            let inflight = state.peers.get(&peer_id).unwrap().inflight_requests;
            let mut effects = Vec::new();

            if inflight < 20 {
                effects.extend(state.update(Action::AssignWork {
                    peer_id: peer_id.clone(),
                }));
            }

            if let Some(action) = pending_actions.pop_front() {
                effects.extend(state.update(action));
            } else if effects.is_empty() && inflight == 0 {
                panic!("DEADLOCK: No inflight requests and no pending actions!");
            }

            // C. Handle All Effects (Recursive Logic)
            for effect in effects {
                match effect {
                    Effect::SendToPeer { cmd, .. } => {
                        if let TorrentCommand::BulkRequest(requests) = *cmd {
                            for (index, begin, length) in requests {
                                // NETWORK SIM: Queue Response
                                let data = vec![0u8; length as usize];
                                pending_actions.push_back(Action::IncomingBlock {
                                    peer_id: peer_id.clone(),
                                    piece_index: index,
                                    block_offset: begin,
                                    data,
                                });
                            }
                        }
                    }
                    Effect::VerifyPiece { piece_index, .. } => {
                        // CPU SIM: Verify OK -> Queue Result
                        pending_actions.push_front(Action::PieceVerified {
                            peer_id: peer_id.clone(),
                            piece_index,
                            valid: true,
                            data: vec![],
                        });
                    }
                    Effect::WriteToDisk { piece_index, .. } => {
                        // DISK SIM: Write OK -> Queue Result
                        pending_actions.push_front(Action::PieceWrittenToDisk {
                            peer_id: peer_id.clone(),
                            piece_index,
                        });
                    }
                    Effect::BroadcastHave { .. } => {
                        // SUCCESS
                        pieces_completed += 1;
                        if pieces_completed % 2000 == 0 {
                            println!("Progress: {}/{}", pieces_completed, num_pieces);
                        }
                    }
                    Effect::DisconnectPeer { .. } | Effect::DisconnectPeerSession { .. } => {
                        panic!("Unexpected Peer Disconnect! Validation likely failed.");
                    }
                    _ => {}
                }
            }
        }

        let duration = start.elapsed();
        println!("State Logic Processed 20k blocks in {:.2?}", duration);

        assert_eq!(pieces_completed, num_pieces);
        assert!(state.piece_manager.need_queue.is_empty());
    }

    #[test]
    fn test_debug_3_blocks_trace() {
        let num_pieces = 3;
        let piece_len = 16_384;

        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(num_pieces);

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.block_manager.set_geometry(
            piece_len as u32,
            (piece_len * num_pieces) as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        let peer_id = "worker_peer".to_string();
        add_peer(&mut state, &peer_id);

        // Setup Peer Bitfield
        let bitfield = vec![0xFF; num_pieces.div_ceil(8)];
        state.update(Action::PeerBitfieldReceived {
            peer_id: peer_id.clone(),
            bitfield,
        });

        // Initialize queue early so we can capture setup effects
        let mut pending_actions = std::collections::VecDeque::new();

        // Capture initial effects from Unchoke (Triggering AssignWork)
        let initial_effects = state.update(Action::PeerUnchoked {
            peer_id: peer_id.clone(),
        });

        // FIX: Feed initial requests into the network queue
        for effect in initial_effects {
            if let Effect::SendToPeer { cmd, .. } = effect {
                if let TorrentCommand::BulkRequest(requests) = *cmd {
                    println!(
                        "   << Setup Effect: SendToPeer BulkRequest with {} requests",
                        requests.len()
                    );
                    for (index, begin, length) in requests {
                        let data = vec![0u8; length as usize];
                        pending_actions.push_back(Action::IncomingBlock {
                            peer_id: peer_id.clone(),
                            piece_index: index,
                            block_offset: begin,
                            data,
                        });
                    }
                }
            }
        }

        state
            .piece_manager
            .update_rarity(state.peers.values().map(|p| &p.bitfield));

        // --- 2. SIMULATION LOOP ---
        let mut pieces_completed = 0;
        let mut loop_count = 0;

        println!("\n=== STARTING TRACE ===");

        while pieces_completed < num_pieces {
            loop_count += 1;
            if loop_count > 50 {
                panic!("STALL! Loop limit reached.");
            }

            let peer = state.peers.get(&peer_id).unwrap();
            println!("\n--- LOOP {} ---", loop_count);
            println!("State Status: {:?}", state.torrent_status);
            println!(
                "Need Q: {:?} | Pending Q: {:?}",
                state.piece_manager.need_queue,
                state.piece_manager.pending_queue.keys()
            );
            println!(
                "Peer Inflight: {} | Peer PendingReqs: {:?}",
                peer.inflight_requests, peer.pending_requests
            );
            println!("Action Queue Size: {}", pending_actions.len());

            let mut effects = Vec::new();

            // Trigger Assignment if pipeline has room
            if peer.inflight_requests < 20 {
                println!(">> Triggering AssignWork");
                effects.extend(state.update(Action::AssignWork {
                    peer_id: peer_id.clone(),
                }));
            }

            // Process One Network Event
            if let Some(action) = pending_actions.pop_front() {
                println!(">> Processing Action: {:?}", action);
                effects.extend(state.update(action));
            }

            // Handle Effects
            for effect in effects {
                match effect {
                    Effect::SendToPeer { cmd, .. } => {
                        println!("   << Effect: SendToPeer {:?}", cmd);
                        if let TorrentCommand::BulkRequest(requests) = *cmd {
                            for (index, begin, length) in requests {
                                let data = vec![0u8; length as usize];
                                pending_actions.push_back(Action::IncomingBlock {
                                    peer_id: peer_id.clone(),
                                    piece_index: index,
                                    block_offset: begin,
                                    data,
                                });
                            }
                        }
                    }
                    Effect::VerifyPiece { piece_index, .. } => {
                        println!("   << Effect: VerifyPiece {}", piece_index);
                        pending_actions.push_front(Action::PieceVerified {
                            peer_id: peer_id.clone(),
                            piece_index,
                            valid: true,
                            data: vec![],
                        });
                    }
                    Effect::WriteToDisk { piece_index, .. } => {
                        println!("   << Effect: WriteToDisk {}", piece_index);
                        pending_actions.push_front(Action::PieceWrittenToDisk {
                            peer_id: peer_id.clone(),
                            piece_index,
                        });
                    }
                    Effect::BroadcastHave { piece_index } => {
                        println!("   << Effect: BroadcastHave {}", piece_index);
                        pieces_completed += 1;
                    }
                    _ => println!("   << Effect: {:?}", effect),
                }
            }
        }
        println!("SUCCESS");
    }

    #[test]
    fn test_reproduce_gap_duplicate_bug() {
        let mut state = super::tests::create_empty_state();
        let piece_len = 16384 * 3;
        let torrent = super::tests::create_dummy_torrent(1);
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state.piece_manager.block_manager.set_geometry(
            piece_len,
            piece_len as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.need_queue = vec![0];

        let peer_id = "gap_peer".to_string();
        let (tx, _) = mpsc::channel(100);
        let mut peer = PeerState::new(peer_id.clone(), tx, state.now);
        peer.peer_id = peer_id.as_bytes().to_vec();
        peer.bitfield = vec![true];
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.am_interested = true;

        // We simulate that we have ALREADY requested Block 0 and Block 2.
        // Block 1 is NOT requested yet.
        // Inflight = 2.
        peer.inflight_requests = 2;
        state.peers.insert(peer_id.clone(), peer);

        let data = vec![0u8; 16384];
        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0, // Block 0 Arrives
            data,
        });

        // Current Logic:
        // - Inflight drops to 1.
        // - AssignWork runs with skips=1.
        // - It sees Block 1 is missing. It uses the skip on Block 1.
        // - It sees Block 2 is missing (it's inflight, but not buffered). It has 0 skips left.
        // - IT REQUESTS BLOCK 2 AGAIN.
        let duplicate_request = effects.iter().any(|e| {
            if let Effect::SendToPeer { cmd, .. } = e {
                if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                    return reqs
                        .iter()
                        .any(|(index, begin, _)| *index == 0 && *begin == 32768);
                }
            }
            false
        });

        assert!(
            duplicate_request,
            "Test Failed: The bug SHOULD exist, but we didn't send a duplicate."
        );
        println!("SUCCESS: Reproduced the GAP bug! Manager re-requested Block 2 because 'skips' logic is flawed.");
    }

    #[test]
    fn test_assign_work_is_sequential() {
        let mut state = create_empty_state();
        let piece_len = 16_384 * 10;
        let torrent = create_dummy_torrent(1);
        state.torrent = Some(torrent);

        // Set geometry so block manager knows we have 10 blocks
        state.piece_manager.set_initial_fields(1, false);
        state.piece_manager.block_manager.set_geometry(
            piece_len,
            piece_len as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        // We need Piece 0
        state.piece_manager.need_queue = vec![0];

        let peer_id = "seq_peer".to_string();
        let (tx, _) = mpsc::channel(100);
        let mut peer = PeerState::new(peer_id.clone(), tx, state.now);

        peer.peer_id = peer_id.as_bytes().to_vec();
        peer.bitfield = vec![true]; // Peer has the piece
        peer.peer_choking = super::ChokeStatus::Unchoke; // Unchoked
        peer.am_interested = true;

        // IMPORTANT: Ensure Peer has 0 inflight and 0 active blocks to prevent skipping
        peer.inflight_requests = 0;
        peer.active_blocks.clear();

        state.peers.insert(peer_id.clone(), peer);

        // This should generate 10 requests for Piece 0 (Blocks 0-9)
        let effects = state.update(Action::AssignWork {
            peer_id: peer_id.clone(),
        });

        let mut expected_offset = 0;
        let mut request_count = 0;

        for effect in effects {
            if let Effect::SendToPeer { cmd, .. } = effect {
                if let TorrentCommand::BulkRequest(requests) = *cmd {
                    for (index, begin, length) in requests {
                        assert_eq!(index, 0, "Should work on Piece 0");
                        assert_eq!(length, 16384, "Block length mismatch");

                        // THE CHECK: Offset must match our expected increment
                        assert_eq!(
                            begin, expected_offset,
                            "Non-sequential request detected! Expected offset {}, got {}. (Shotgunning?)",
                            expected_offset, begin
                        );

                        expected_offset += 16384;
                        request_count += 1;
                    }
                }
            }
        }

        // Ensure we actually tested something
        assert_eq!(request_count, 10, "Expected 10 requests to fill the piece");
        println!("SUCCESS: Generated 10 sequential requests for Piece 0.");
    }

    #[test]
    fn test_assign_work_multi_piece_saturation() {
        // We need > 50 blocks to test the MAX_PIPELINE_DEPTH limit.
        let mut state = create_empty_state();
        let piece_len = 16_384 * 4;
        let num_pieces = 15;
        let torrent = create_dummy_torrent(num_pieces);
        state.torrent = Some(torrent);

        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.block_manager.set_geometry(
            piece_len,
            (piece_len * num_pieces as u32) as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        // All pieces are needed
        state.piece_manager.need_queue = (0..num_pieces as u32).collect();

        let peer_id = "multi_piece_peer".to_string();
        let (tx, _) = mpsc::channel(100);
        let mut peer = PeerState::new(peer_id.clone(), tx, state.now);

        peer.peer_id = peer_id.as_bytes().to_vec();
        peer.bitfield = vec![true; num_pieces];
        peer.peer_choking = super::ChokeStatus::Unchoke;
        peer.am_interested = true;
        peer.inflight_requests = 0;
        peer.active_blocks.clear();

        // We manually put all pieces into the pending queue.
        for i in 0..num_pieces as u32 {
            peer.pending_requests.insert(i);
        }

        state.peers.insert(peer_id.clone(), peer);

        // Pipeline Depth is 50.
        // We need 60 blocks total (15 pieces * 4 blocks).
        // We expect the first 50 blocks to be requested.
        let effects = state.update(Action::AssignWork {
            peer_id: peer_id.clone(),
        });

        let mut requests = Vec::new();
        for effect in effects {
            if let Effect::SendToPeer { cmd, .. } = effect {
                if let TorrentCommand::BulkRequest(ref reqs) = *cmd {
                    requests.extend(reqs.iter().map(|(i, b, _)| (*i, *b)));
                }
            }
        }

        assert_eq!(
            requests.len(),
            60,
            "Should request all available blocks (60) as it's less than pipeline depth ({})",
            super::MAX_PIPELINE_DEPTH
        );

        // CHECK 1: Sequential Offsets
        for piece_idx in 0..num_pieces as u32 {
            let offsets: Vec<u32> = requests
                .iter()
                .filter(|(i, _)| *i == piece_idx)
                .map(|(_, off)| *off)
                .collect();

            if !offsets.is_empty() {
                let mut sorted_offsets = offsets.clone();
                sorted_offsets.sort();
                assert_eq!(
                    offsets, sorted_offsets,
                    "Non-sequential blocks detected for Piece {}! Got {:?}",
                    piece_idx, offsets
                );
            }
        }

        // CHECK 2: Deterministic Piece Order (The "Sort" Fix Check)
        // Piece 0 must start before Piece 2.
        let piece_0_start = requests.iter().position(|(i, _)| *i == 0);
        let piece_2_start = requests.iter().position(|(i, _)| *i == 2);

        if let (Some(p0), Some(p2)) = (piece_0_start, piece_2_start) {
            assert!(
                p0 < p2,
                "Random Order Detected! Pending requests must be sorted."
            );
        }

        println!("SUCCESS: Pipeline saturated at 50 requests with sequential ordering.");
    }

    // V2 / HYBRID LOGIC TESTS

    #[test]
    fn test_v2_hybrid_boundary_routing() {
        let mut state = create_empty_state();

        // Setup: Piece 0, Length 32768 (Spans 2 Files of 16384 each)
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 32768;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(32768, 32768, HashMap::new(), false);

        let root_a = vec![0xAA; 32]; // File A (0-16384)
        let root_b = vec![0xBB; 32]; // File B (16384-32768)

        state.piece_to_roots.insert(
            0,
            vec![
                V2RootInfo {
                    file_offset: 0,
                    length: 16384,
                    root_hash: root_a.clone(),
                    file_index: 0,
                },
                V2RootInfo {
                    file_offset: 16384,
                    length: 16384,
                    root_hash: root_b.clone(),
                    file_index: 0,
                },
            ],
        );
        state.v2_proofs.insert(0, vec![0xFF; 32]); // Proof ready

        // --- SCENARIO 1: Complete via Offset 16384 (Should match Root B) ---

        state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0u8; 16384],
        });

        let effects_b = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 16384,
            data: vec![0u8; 16384],
        });

        let verified_b = effects_b
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { root_hash, .. } if root_hash == &root_b));
        assert!(
            verified_b,
            "Completion at offset 16384 should verify against Root B"
        );

        // --- SCENARIO 2: Complete via Offset 0 (Should match Root A) ---

        // Reset State for clean run
        state.piece_manager = PieceManager::new();
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(32768, 32768, HashMap::new(), false);

        state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 16384,
            data: vec![0u8; 16384],
        });

        let effects_a = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0u8; 16384],
        });

        let verified_a = effects_a
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { root_hash, .. } if root_hash == &root_a));
        assert!(
            verified_a,
            "Completion at offset 0 should verify against Root A"
        );
    }

    #[test]
    fn test_v2_deferred_verification_with_offset() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(10);
        torrent.info.piece_length = 4;
        torrent.info.pieces = Vec::new();

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(10, false);
        state
            .piece_manager
            .set_geometry(4, 40, HashMap::new(), false);

        let root_target = vec![0xCC; 32];
        // FIX: file_len (8) > piece_len (4) forces buffering
        state.piece_to_roots.insert(
            5,
            vec![V2RootInfo {
                file_offset: 0,
                length: 8,
                root_hash: root_target.clone(),
                file_index: 0,
            }],
        );

        let _effects_data = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 5,
            block_offset: 0,
            data: vec![1, 2, 3, 4],
        });

        assert!(
            state.v2_pending_data.contains_key(&5),
            "Data must buffer for multi-piece files without proof"
        );

        let effects_proof = state.update(Action::MerkleProofReceived {
            peer_id: "peer1".into(),
            piece_index: 5,
            proof: vec![0xEE; 32],
        });

        assert!(effects_proof
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. })));
    }

    #[test]
    fn test_v2_verification_failure() {
        let mut state = create_empty_state();
        // Setup simple 1-piece torrent
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(1024, 1024, HashMap::new(), false);

        let root_hash = vec![0xAA; 32];
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 1024,
                root_hash: root_hash.clone(),
                file_index: 0,
            }],
        );

        // Proof arrives first
        state.v2_proofs.insert(0, vec![0xFF; 32]);

        // Incoming block with "bad" data
        let effects = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0x00; 1024], // Junk data
        });

        // Effect should be VerifyPieceV2
        assert!(effects
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. })));

        // Simulate the CPU worker returning "valid: false"
        let verify_effects = state.update(Action::PieceVerified {
            peer_id: "peer1".into(),
            piece_index: 0,
            valid: false, // <--- FAILURE
            data: vec![],
        });

        // Expect disconnection or punishment
        let disconnected = verify_effects
            .iter()
            .any(|e| matches!(e, Effect::DisconnectPeer { .. }));
        assert!(
            disconnected,
            "Peer should be disconnected on V2 verification failure"
        );
    }

    #[test]
    fn test_v2_verification_failure_disconnects_peer() {
        // GIVEN: A V2 piece where verification fails (e.g. bad data sent)
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(1024, 1024, HashMap::new(), false);

        let root_hash = vec![0xAA; 32];
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 1024,
                root_hash: root_hash.clone(),
                file_index: 0,
            }],
        );

        state.update(Action::MerkleProofReceived {
            peer_id: "peer1".into(),
            piece_index: 0,
            proof: vec![0xFF; 32],
        });

        let effects = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0x00; 1024],
        });

        // Assert: Verification was attempted
        assert!(effects
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. })));

        let verify_effects = state.update(Action::PieceVerified {
            peer_id: "peer1".into(),
            piece_index: 0,
            valid: false,
            data: vec![],
        });

        // THEN: Peer should be disconnected
        let disconnected = verify_effects
            .iter()
            .any(|e| matches!(e, Effect::DisconnectPeer { .. }));
        assert!(
            disconnected,
            "Peer should be disconnected on V2 verification failure"
        );

        // THEN: Assembly should be reset (checked via internal state or subsequent behavior)
        // (In this mock state, reset_piece_assembly is a void operation, but the effect confirms the logic path)
    }

    #[test]
    fn test_v2_state_cleanup_after_success() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 4;
        torrent.info.pieces = Vec::new();
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(4, 4, HashMap::new(), false);

        // FIX: Set file_len (8) > piece_len (4) to force the V2 workflow (buffer + proof)
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 8,
                root_hash: vec![0xAA; 32],
                file_index: 0,
            }],
        );

        state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![1, 2, 3, 4],
        });
        assert!(
            state.v2_pending_data.contains_key(&0),
            "Data should be buffered for multi-piece file"
        );

        state.update(Action::MerkleProofReceived {
            peer_id: "peer1".into(),
            piece_index: 0,
            proof: vec![0xBB; 32],
        });

        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Pending data consumed"
        );

        state.update(Action::PieceVerified {
            peer_id: "peer1".into(),
            piece_index: 0,
            valid: true,
            data: vec![1, 2, 3, 4],
        });

        assert!(
            !state.v2_proofs.contains_key(&0),
            "Proof cache cleared after verification"
        );
    }

    #[test]
    fn test_v2_duplicate_handling_robustness() {
        // GIVEN: A peer that sends duplicate proofs/data
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(1024, 1024, HashMap::new(), false);
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 1024,
                root_hash: vec![0xAA; 32],
                file_index: 0,
            }],
        );

        state.update(Action::MerkleProofReceived {
            peer_id: "peer1".into(),
            piece_index: 0,
            proof: vec![0xBB; 32],
        });

        let effects_dup = state.update(Action::MerkleProofReceived {
            peer_id: "peer1".into(),
            piece_index: 0,
            proof: vec![0xBB; 32],
        });
        // Duplicate proof with no data buffered usually results in DoNothing or effectively a no-op update
        assert!(effects_dup.iter().all(|e| matches!(e, Effect::DoNothing)));

        let effects_data = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0xCC; 1024],
        });

        let verify_triggered = effects_data
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. }));
        assert!(
            verify_triggered,
            "Verification should still trigger after duplicate proofs"
        );

        // Note: The manager usually transitions `last_activity` to VerifyingPiece.
        // We verify that it doesn't try to double-verify or panic.
        let _effects_data_dup = state.update(Action::IncomingBlock {
            peer_id: "peer1".into(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0xCC; 1024],
        });

        // Logic: If last_activity is VerifyingPiece, IncomingBlock usually returns DoNothing or ignores.
        // We just assert it didn't panic and logic held.
    }

    #[test]
    fn test_v2_scale_1000_deferred_blocks() {
        // GIVEN: A torrent with 1000 V2 pieces
        let mut state = create_empty_state();
        let num_pieces = 1000;
        let piece_len = 1024; // Defined here for scope visibility

        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = Vec::new();
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.set_geometry(
            piece_len as u32,
            (piece_len * num_pieces) as u64,
            HashMap::new(),
            false,
        );

        // Map all pieces to a dummy root
        let root = vec![0xAA; 32];
        let total_file_len = (num_pieces as u64) * (piece_len as u64);

        for i in 0..num_pieces {
            // All pieces belong to one large file (0 to total_file_len)
            state.piece_to_roots.insert(
                i as u32,
                vec![V2RootInfo {
                    file_offset: 0,
                    length: total_file_len,
                    root_hash: root.clone(),
                    file_index: 0,
                }],
            );
        }

        let peer_id = "worker_peer".to_string();
        add_peer(&mut state, &peer_id);

        // We simulate a peer sending 1000 blocks rapidly.
        for i in 0..num_pieces {
            state.update(Action::IncomingBlock {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                block_offset: 0,
                data: vec![0u8; 1024],
            });
        }

        // CHECK: We should have 1000 items pending in memory
        assert_eq!(
            state.v2_pending_data.len(),
            1000,
            "Should buffer 1000 pieces awaiting proofs"
        );

        // Now the proofs arrive. This tests if the system can drain the queue efficiently.
        let mut verify_count = 0;
        for i in 0..num_pieces {
            let effects = state.update(Action::MerkleProofReceived {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                proof: vec![0xFF; 32],
            });

            if effects
                .iter()
                .any(|e| matches!(e, Effect::VerifyPieceV2 { .. }))
            {
                verify_count += 1;
            }
        }

        // CHECK: All 1000 should have triggered verification
        assert_eq!(
            verify_count, 1000,
            "All 1000 pieces should trigger verification after proofs arrive"
        );

        // CHECK: Buffer should be empty (moved to verification)
        assert!(
            state.v2_pending_data.is_empty(),
            "Pending buffer should be drained"
        );
    }

    #[test]
    fn test_scale_1000_blocks_pure_v2() {
        let mut state = create_empty_state();
        let num_pieces = 1000;
        let piece_len = 1024;
        let total_len = (num_pieces as i64) * (piece_len as i64);

        let mut torrent = create_dummy_torrent(0);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.length = total_len;
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new();

        // Setup V2 File Tree to ensure rebuild_v2_mappings populates piece_to_roots
        let root = vec![0xBB; 32];
        let mut file_meta = HashMap::new();
        file_meta.insert(
            "length".as_bytes().to_vec(),
            serde_bencode::value::Value::Int(total_len),
        );
        file_meta.insert(
            "pieces root".as_bytes().to_vec(),
            serde_bencode::value::Value::Bytes(root.clone()),
        );

        let mut file_node = HashMap::new();
        file_node.insert(
            "".as_bytes().to_vec(),
            serde_bencode::value::Value::Dict(file_meta),
        );

        let mut root_node = HashMap::new();
        root_node.insert(
            "test_torrent".as_bytes().to_vec(),
            serde_bencode::value::Value::Dict(file_node),
        );
        torrent.info.file_tree = Some(serde_bencode::value::Value::Dict(root_node));

        // Calling this will now correctly build piece_to_roots for you
        state.update(Action::MetadataReceived {
            torrent: Box::new(torrent.clone()),
            metadata_length: 5000,
        });

        state.torrent_status = TorrentStatus::Standard;

        let root = vec![0xBB; 32];
        let total_file_len = (num_pieces as u64) * (piece_len as u64);

        for i in 0..num_pieces {
            // Map every piece to a single large 1000-piece file
            state.piece_to_roots.insert(
                i as u32,
                vec![V2RootInfo {
                    file_offset: 0,
                    length: total_file_len,
                    root_hash: root.clone(),
                    file_index: 0,
                }],
            );
        }

        let peer_id = "v2_worker".to_string();
        add_peer(&mut state, &peer_id);
        state.update(Action::PeerUnchoked {
            peer_id: peer_id.clone(),
        });

        for i in 0..num_pieces {
            state.update(Action::IncomingBlock {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                block_offset: 0,
                data: vec![0u8; piece_len as usize],
            });
        }
        assert_eq!(
            state.v2_pending_data.len(),
            1000,
            "Pure V2: Should buffer pieces for large files"
        );

        let mut verify_count = 0;
        for i in 0..num_pieces {
            let effects = state.update(Action::MerkleProofReceived {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                proof: vec![0xEE; 32],
            });
            if effects
                .iter()
                .any(|e| matches!(e, Effect::VerifyPieceV2 { .. }))
            {
                verify_count += 1;
            }
        }
        assert_eq!(verify_count, 1000);
    }

    #[test]
    fn test_v2_memory_cap_enforcement() {
        let mut state = create_empty_state();

        // GIVEN: A torrent with HUGE pieces (500 MB)
        // This tricks the cleanup logic into setting a very small item limit.
        // Limit = 1GB / 500MB = 2 items allowed.
        let mut torrent = create_dummy_torrent(10);
        torrent.info.piece_length = 500 * 1024 * 1024; // 500 MB
        state.torrent = Some(torrent);

        // We use small data vectors so we don't actually crash the test runner,
        // but the state machine counts them as "full pieces".
        for i in 0..3 {
            state.v2_pending_data.insert(i, (0, vec![0u8; 10]));
        }

        assert_eq!(
            state.v2_pending_data.len(),
            3,
            "Sanity check: 3 items inserted"
        );

        state.update(Action::Cleanup);

        // THEN: The buffer should be cleared because 3 > 2 (Limit)
        assert!(state.v2_pending_data.is_empty(),
            "Cleanup should verify that 3 items exceeds the calculated limit for 500MB pieces (limit=2), and clear the buffer");
    }

    #[test]
    fn test_hybrid_v1_v2_interop() {
        // GIVEN: A State with 2 pieces
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);

        state.piece_manager.set_initial_fields(2, false);
        state
            .piece_manager
            .set_geometry(1024, 2048, HashMap::new(), false);

        // CONFIGURATION: Hybrid Setup
        // Piece 0: Has a V2 Root
        let root = vec![0xAA; 32];

        // FIX: Set file length (2048) > piece_length (1024).
        // This ensures get_local_v2_hash returns None (requires proof/layers),
        // forcing the system to fall back to the V1 hashes provided by create_dummy_torrent.
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 2048,
                root_hash: root.clone(),
                file_index: 0,
            }],
        );

        // Piece 1: NO Root (V1 Only)

        let peer_id = "hybrid_peer".to_string();
        add_peer(&mut state, &peer_id);

        // --- CASE 4: V1 Peer -> V2 Piece (The "Cooperative" Case) ---
        // Peer B (Legacy) sends data for Piece 0 (V2).
        // It CANNOT send a proof.
        // BEHAVIOR CHANGE: Since we have V1 hashes (from create_dummy_torrent),
        // we should FALL BACK to V1 verification immediately, NOT buffer.

        let effects_4_data = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![1u8; 1024],
        });

        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Piece 0 should NOT buffer; it should verify via V1 fallback"
        );

        // Note: VerifyPiece (V1) is different from VerifyPieceV2
        let verified_v1 = effects_4_data
            .iter()
            .any(|e| matches!(e, Effect::VerifyPiece { .. }));
        assert!(
            verified_v1,
            "Should have fallen back to V1 verification (Effect::VerifyPiece)"
        );
    }

    #[test]
    fn test_v2_full_completion_lifecycle() {
        let mut state = create_empty_state();
        let num_pieces = 4;
        let piece_len = 1024;
        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = Vec::new(); // Pure V2

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.set_geometry(
            piece_len as u32,
            (piece_len * num_pieces) as u64,
            HashMap::new(),
            false,
        );
        state.torrent_status = TorrentStatus::Standard;

        let root = vec![0xAA; 32];
        // FIX: Set file length to force the standard V2 proof workflow (buffer -> proof -> verify)
        let file_len = (piece_len * 2) as u64;
        for i in 0..num_pieces {
            state.piece_to_roots.insert(
                i as u32,
                vec![V2RootInfo {
                    file_offset: 0,
                    length: file_len,
                    root_hash: root.clone(),
                    file_index: 0,
                }],
            );
        }

        let peer_id = "seeder".to_string();
        add_peer(&mut state, &peer_id);

        for i in 0..num_pieces {
            // Data arrives and is buffered because it is a multi-piece file without a proof
            state.update(Action::IncomingBlock {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                block_offset: 0,
                data: vec![1u8; piece_len],
            });

            // Proof arrives, triggering the V2 verification effect
            let effects = state.update(Action::MerkleProofReceived {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                proof: vec![0xFF; 32],
            });

            assert!(
                effects
                    .iter()
                    .any(|e| matches!(e, Effect::VerifyPieceV2 { .. })),
                "Proof arrival should trigger VerifyPieceV2 for piece {}",
                i
            );
        }

        assert!(
            state.v2_pending_data.is_empty(),
            "All pending data should be moved to verification"
        );
    }

    #[test]
    fn test_v2_cleanup_on_completion_race() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 1024;
        torrent.info.pieces = Vec::new();
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(1024, 1024, HashMap::new(), false);

        // FIX: Set file_len (2048) > piece_length (1024) to force buffering
        // Small files (<= piece_len) verify immediately using the root as the leaf.
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 2048,
                root_hash: vec![0xAA; 32],
                file_index: 0,
            }],
        );
        let peer_id = "racer".to_string();
        add_peer(&mut state, &peer_id);

        state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![1u8; 1024],
        });
        assert!(
            state.v2_pending_data.contains_key(&0),
            "Sanity: Data buffered"
        );

        state.update(Action::PieceVerified {
            peer_id: peer_id.clone(),
            piece_index: 0,
            valid: true,
            data: vec![1u8; 1024],
        });

        // Manually mark as done in bitfield to simulate WriteToDisk completion
        state.piece_manager.bitfield[0] = crate::torrent_manager::piece_manager::PieceStatus::Done;

        // CHECK 1: Did we clean up the pending data?
        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Leak: Pending data should be removed immediately upon verification"
        );

        state.update(Action::MerkleProofReceived {
            peer_id: peer_id.clone(),
            piece_index: 0,
            proof: vec![0xFF; 32],
        });

        // CHECK 2: Did we ignore the late proof?
        assert!(
            !state.v2_proofs.contains_key(&0),
            "Leak: Late proofs for Done pieces should be ignored, not cached"
        );
    }

    #[test]
    fn test_v2_cleanup_on_failure() {
        // GIVEN: A torrent with buffered data
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(1024, 1024, HashMap::new(), false);
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 1024,
                root_hash: vec![0xAA; 32],
                file_index: 0,
            }],
        );

        let peer_id = "bad_actor".to_string();
        add_peer(&mut state, &peer_id);

        state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![1u8; 1024],
        });

        state.update(Action::PieceVerified {
            peer_id: peer_id.clone(),
            piece_index: 0,
            valid: false, // <--- FAILURE
            data: vec![],
        });

        // CHECK: Memory should be freed immediately
        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Cleanup: Pending data must be removed even if verification fails"
        );
        assert!(
            !state.v2_proofs.contains_key(&0),
            "Cleanup: Proofs must be removed even if verification fails"
        );
    }

    #[test]
    fn test_hybrid_swarm_interop() {
        // GIVEN: A Hybrid Torrent with 4 pieces
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(4);
        torrent.info.piece_length = 1024;
        state.torrent = Some(torrent);

        state.piece_manager.set_initial_fields(4, false);
        state
            .piece_manager
            .set_geometry(1024, 4096, HashMap::new(), false);

        // CONFIGURATION:
        // Piece 0: V2 (Has Root)
        let root = vec![0xAA; 32];
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 1024,
                root_hash: root.clone(),
                file_index: 0,
            }],
        );

        let peer_a = "v2_peer_A".to_string();
        add_peer(&mut state, &peer_a);

        // --- CASE 1: V2 Peer -> V2 Piece ---
        // Peer A sends data.
        // Because V1 hashes exist, the client will likely verify immediately via V1
        // instead of waiting for the proof. This is valid/desired behavior.
        // OR: If the file is small (<= piece size), it verifies via V2 immediately using the root as the leaf.
        let effects_data = state.update(Action::IncomingBlock {
            peer_id: peer_a.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![1u8; 1024],
        });

        let effects_proof = state.update(Action::MerkleProofReceived {
            peer_id: peer_a.clone(),
            piece_index: 0,
            proof: vec![0xFF; 32],
        });

        // CHECK: Did we verify at all?
        // We accept:

        let verified_data_v1 = effects_data
            .iter()
            .any(|e| matches!(e, Effect::VerifyPiece { .. }));
        let verified_data_v2 = effects_data
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. }));
        let verified_proof_v2 = effects_proof
            .iter()
            .any(|e| matches!(e, Effect::VerifyPieceV2 { .. }));

        assert!(verified_data_v1 || verified_data_v2 || verified_proof_v2,
            "Case 1 Fail: Should have verified via V1/V2 (data) OR V2 (proof). DataV1: {}, DataV2: {}, ProofV2: {}",
            verified_data_v1, verified_data_v2, verified_proof_v2);
    }

    #[test]
    fn test_v2_magnet_metadata_sequence() {
        // GIVEN: An empty state (simulating a fresh V2 Magnet connection)
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/tmp/test"));
        state.torrent_status = TorrentStatus::AwaitingMetadata;

        // Construct a V2-Only Torrent (Empty V1 pieces, Has V2 Roots)
        let mut torrent = create_dummy_torrent(5);
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new(); // V2 has empty pieces string
        torrent.info.piece_length = 16384;
        torrent.info.length = 16384 * 5; // 5 Pieces

        // Ensure the name matches what we put in the tree
        let filename = "test_torrent".to_string();
        torrent.info.name = filename.clone();

        // Setup V2 Root (Critical for piece_to_roots population)
        let root = vec![0xAA; 32];

        // Mock the V2 File Tree Structure
        // Structure: { "filename": { "": { "pieces root": ..., "length": ... } } }
        use serde_bencode::value::Value;

        let mut file_metadata = std::collections::HashMap::new();
        file_metadata.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(root.clone()),
        );
        file_metadata.insert(
            "length".as_bytes().to_vec(),
            Value::Int(torrent.info.length),
        );

        let mut dir_node = std::collections::HashMap::new();
        dir_node.insert("".as_bytes().to_vec(), Value::Dict(file_metadata));

        let mut tree = std::collections::HashMap::new();
        tree.insert(filename.as_bytes().to_vec(), Value::Dict(dir_node));

        torrent.info.file_tree = Some(Value::Dict(tree));

        // WHEN: Metadata is received
        let action = Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 12345,
        };
        let effects = state.update(action);

        // THEN 1: Sequencing - Should transition to Validating and Init Storage
        assert_eq!(state.torrent_status, TorrentStatus::Validating);
        assert!(effects.iter().any(|e| matches!(e, Effect::StartValidation)));

        // THEN 2: V2 Initialization - Piece count must be 5 (calculated from length)
        assert_eq!(
            state.piece_manager.bitfield.len(),
            5,
            "Failed to calculate piece count for V2 torrent (likely initialized to 0)"
        );

        // THEN 3: V2 State - piece_to_roots must be populated
        assert!(
            !state.piece_to_roots.is_empty(),
            "Failed to populate V2 roots from metadata"
        );

        let roots_for_piece_0 = state.piece_to_roots.get(&0).unwrap();
        assert_eq!(
            roots_for_piece_0[0].root_hash, root,
            "Piece 0 should map to our mock root"
        );
    }

    #[test]
    fn test_v2_magnet_metadata_sequence_multi_file() {
        // GIVEN: An empty state (simulating a fresh V2 Magnet connection)
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/tmp/test"));
        state.torrent_status = TorrentStatus::AwaitingMetadata;

        // Construct a V2-Only Torrent
        // 2 Files, 1 Piece each. Total 2 Pieces.
        let mut torrent = create_dummy_torrent(2);
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new(); // V2 has empty pieces string
        torrent.info.piece_length = 16384;
        torrent.info.length = 0; // Unused in multi-file usually, but safer to leave 0 or sum

        let dir_name = "multi_v2_download".to_string();
        torrent.info.name = dir_name.clone();

        // define file properties
        let len_a = 16384;
        let len_b = 16384;
        let root_a = vec![0xAA; 32];
        let root_b = vec![0xBB; 32];

        torrent.info.files = vec![
            crate::torrent_file::InfoFile {
                length: len_a,
                path: vec![dir_name.clone(), "file_a.txt".to_string()],
                md5sum: None,
                attr: None,
            },
            crate::torrent_file::InfoFile {
                length: len_b,
                path: vec![dir_name.clone(), "file_b.txt".to_string()],
                md5sum: None,
                attr: None,
            },
        ];

        // Structure: { "dir_name": { "file_a.txt": { "": metadata }, "file_b.txt": { "": metadata } } }
        use serde_bencode::value::Value;

        // Leaf A
        let mut meta_a = std::collections::HashMap::new();
        meta_a.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(root_a.clone()),
        );
        meta_a.insert("length".as_bytes().to_vec(), Value::Int(len_a));
        let mut node_a = std::collections::HashMap::new();
        node_a.insert("".as_bytes().to_vec(), Value::Dict(meta_a));

        // Leaf B
        let mut meta_b = std::collections::HashMap::new();
        meta_b.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(root_b.clone()),
        );
        meta_b.insert("length".as_bytes().to_vec(), Value::Int(len_b));
        let mut node_b = std::collections::HashMap::new();
        node_b.insert("".as_bytes().to_vec(), Value::Dict(meta_b));

        // Directory
        let mut dir_content = std::collections::HashMap::new();
        dir_content.insert("file_a.txt".as_bytes().to_vec(), Value::Dict(node_a));
        dir_content.insert("file_b.txt".as_bytes().to_vec(), Value::Dict(node_b));

        // Root
        let mut tree = std::collections::HashMap::new();
        tree.insert(dir_name.as_bytes().to_vec(), Value::Dict(dir_content));

        torrent.info.file_tree = Some(Value::Dict(tree));

        // WHEN: Metadata is received
        let action = Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 500,
        };
        let _effects = state.update(action);

        // THEN 1: Transitions
        assert_eq!(state.torrent_status, TorrentStatus::Validating);

        // THEN 2: Piece Count Calculation (16384+16384 / 16384 = 2)
        assert_eq!(
            state.piece_manager.bitfield.len(),
            2,
            "Should calculate 2 pieces from file sizes"
        );

        // THEN 3: Root Mapping
        // Piece 0 -> File A -> Root A
        let roots_0 = state.piece_to_roots.get(&0).expect("Piece 0 missing roots");
        assert!(
            roots_0.iter().any(|r| r.root_hash == root_a),
            "Piece 0 must map to Root A"
        );

        // Piece 1 -> File B -> Root B
        let roots_1 = state.piece_to_roots.get(&1).expect("Piece 1 missing roots");
        assert!(
            roots_1.iter().any(|r| r.root_hash == root_b),
            "Piece 1 must map to Root B"
        );

        // Piece 1 -> File B -> Root B
        let roots_1 = state.piece_to_roots.get(&1).expect("Piece 1 missing roots");
        assert!(
            roots_1.iter().any(|r| r.root_hash == root_b),
            "Piece 1 must map to Root B"
        );
    }

    #[test]
    fn test_scale_1000_blocks_hybrid() {
        println!("\n=== STARTING SCALE TEST: HYBRID (1000 Blocks) ===");

        let mut state = create_empty_state();
        let num_pieces = 1000;
        let piece_len = 1024;

        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.length = (num_pieces as i64) * (piece_len as i64);
        torrent.info.meta_version = Some(2);

        state.update(Action::MetadataReceived {
            torrent: Box::new(torrent.clone()),
            metadata_length: 5000,
        });
        state.torrent_status = TorrentStatus::Standard;

        let root = vec![0xAA; 32];
        // FIX: Define total file length to exceed one piece length
        let total_file_len = (num_pieces as u64) * (piece_len as u64);
        for i in 0..num_pieces {
            // Map to a single large file to test V1/V2 interop on large structures
            state.piece_to_roots.insert(
                i as u32,
                vec![V2RootInfo {
                    file_offset: 0,
                    length: total_file_len,
                    root_hash: root.clone(),
                    file_index: 0,
                }],
            );
        }

        let peer_id = "hybrid_worker".to_string();
        add_peer(&mut state, &peer_id);
        state.update(Action::PeerUnchoked {
            peer_id: peer_id.clone(),
        });

        let mut immediate_verifications = 0;

        for i in 0..num_pieces {
            let effects = state.update(Action::IncomingBlock {
                peer_id: peer_id.clone(),
                piece_index: i as u32,
                block_offset: 0,
                data: vec![0u8; piece_len],
            });

            if effects
                .iter()
                .any(|e| matches!(e, Effect::VerifyPiece { .. }))
            {
                immediate_verifications += 1;
            }
        }

        assert_eq!(
            immediate_verifications, 1000,
            "Hybrid: All 1000 pieces should verify immediately via V1 fallback"
        );
        assert!(
            state.v2_pending_data.is_empty(),
            "Hybrid: Buffer should be empty"
        );
    }

    #[test]
    fn test_v2_verification_with_nonzero_file_offset() {
        let mut state = create_empty_state();

        // Setup: 2 Pieces total.
        // Piece 0: File A (Padding/Skip)
        // Piece 1: File B (The one we want to verify)
        let piece_len = 1024;
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = piece_len;
        state.torrent = Some(torrent);

        state.piece_manager.set_initial_fields(2, false);
        state
            .piece_manager
            .set_geometry(1024, 2048, HashMap::new(), false);

        // Root for File B
        let root_b = vec![0xBB; 32];

        // Map Piece 1 to File B, which starts at 1024 (Piece 1's start)
        // This implies File A occupied 0..1024.
        state.piece_to_roots.insert(
            1,
            vec![V2RootInfo {
                file_offset: 1024,
                length: 1024,
                root_hash: root_b.clone(),
                file_index: 0,
            }],
        );

        let peer_id = "offset_tester".to_string();
        add_peer(&mut state, &peer_id);

        // The proof corresponds to the FIRST piece of File B (Relative Index 0)
        let proof = vec![0xFF; 32]; // Dummy proof
        state.update(Action::MerkleProofReceived {
            peer_id: peer_id.clone(),
            piece_index: 1, // GLOBAL Index 1
            proof: proof.clone(),
        });

        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 1, // GLOBAL Index 1
            block_offset: 0,
            data: vec![0xBB; 1024],
        });

        // If your logic is correct, it should spawn VerifyPieceV2.
        // Inspect the arguments passed to it.

        let verify_effect = effects.iter().find_map(|e| {
            if let Effect::VerifyPieceV2 {
                piece_index,
                root_hash,
                ..
            } = e
            {
                Some((piece_index, root_hash))
            } else {
                None
            }
        });

        assert!(verify_effect.is_some(), "Should trigger V2 verification");

        let (idx, hash) = verify_effect.unwrap();
        assert_eq!(hash, &root_b, "Should verify against Root B");

        // CRITICAL CHECK:
        // If you updated the enum to have `relative_index`, check that here.
        // If you are relying on the manager to calculate it, this test ensures
        // the manager receives the correct GLOBAL index (1) to look up the file info later.
        assert_eq!(
            *idx, 1,
            "Effect should carry Global Index 1 for state tracking"
        );
    }

    #[test]
    fn test_v2_local_lookup_optimization() {
        use sha2::Digest;
        use std::collections::HashMap;

        // GOAL: Verify that a Pure V2 torrent can verify data using LOCAL piece_layers

        let mut state = create_empty_state();
        let piece_len = 16384;
        let num_pieces = 1;

        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = Vec::new(); // Pure V2 (Disable V1 fallback)
        torrent.info.meta_version = Some(2);

        let data = vec![0xAA; piece_len];
        let leaf_hash = sha2::Sha256::digest(&data).to_vec();
        let root = leaf_hash.clone();

        let mut layer_map = HashMap::new();
        layer_map.insert(
            root.clone(),
            serde_bencode::value::Value::Bytes(leaf_hash.clone()),
        );
        torrent.piece_layers = Some(serde_bencode::value::Value::Dict(layer_map));

        state.torrent = Some(torrent);

        // CRITICAL FIX: Initialize PieceManager so it accepts the block!
        state.piece_manager.set_initial_fields(num_pieces, false);
        state
            .piece_manager
            .set_geometry(piece_len as u32, piece_len as u64, HashMap::new(), false);

        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: piece_len as u64,
                root_hash: root.clone(),
                file_index: 0,
            }],
        );

        let peer_id = "optimized_peer".to_string();
        add_peer(&mut state, &peer_id);

        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: data.clone(),
        });

        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Optimization Fail: Data buffered instead of verifying!"
        );

        let verified = effects.iter().any(|e| {
            if let Effect::VerifyPieceV2 { root_hash, .. } = e {
                *root_hash == leaf_hash
            } else {
                false
            }
        });
        assert!(
            verified,
            "Optimization Fail: VerifyPieceV2 was not triggered immediately."
        );
    }

    #[test]
    fn test_repro_v2_proof_priority_bug() {
        use sha2::{Digest, Sha256};

        let mut state = create_empty_state();
        let piece_len = 1024;

        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new();

        let data = vec![0xAA; 1024];
        let leaf_hash = Sha256::digest(&data).to_vec();
        let file_root = vec![0xBB; 32]; // Different from leaf

        let mut layer_map = std::collections::HashMap::new();
        layer_map.insert(
            file_root.clone(),
            serde_bencode::value::Value::Bytes(leaf_hash.clone()),
        );
        torrent.piece_layers = Some(serde_bencode::value::Value::Dict(layer_map));
        state.torrent = Some(torrent);

        // C. FIX: Set file_len to 2 * piece_len to bypass small-file optimization
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 2048,
                root_hash: file_root.clone(),
                file_index: 0,
            }],
        );
        state.piece_manager.set_initial_fields(2, false);
        state
            .piece_manager
            .set_geometry(1024, 2048, HashMap::new(), false);

        let peer_id = "bug_tester".to_string();
        add_peer(&mut state, &peer_id);

        // D. Data is now buffered because it's a large file and we lack a network proof
        state.v2_pending_data.insert(0, (0, data.clone()));

        // E. Receive Proof - should now correctly prioritize the leaf_hash from metadata
        let effects = state.update(Action::MerkleProofReceived {
            peer_id: peer_id.clone(),
            piece_index: 0,
            proof: vec![0xFF; 32],
        });

        let verify_op = effects.iter().find_map(|e| {
            if let Effect::VerifyPieceV2 { root_hash, .. } = e {
                Some(root_hash)
            } else {
                None
            }
        });

        assert_eq!(
            verify_op.unwrap(),
            &leaf_hash,
            "Should prioritize Leaf Hash over File Root for multi-piece files"
        );
    }

    #[test]
    fn test_incoming_block_uses_local_leaf_hash_priority() {
        use sha2::{Digest, Sha256};
        use std::collections::HashMap;

        let mut state = create_empty_state();
        let piece_len = 1024;
        let num_pieces = 1;

        // Construct Pure V2 Torrent
        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = Vec::new(); // Pure V2 (No V1 Fallback)
        torrent.info.meta_version = Some(2);

        let data = vec![0xAA; piece_len];
        let leaf_hash = Sha256::digest(&data).to_vec();

        // V2 PROTOCOL RULE: For a file that fits in one piece,
        // the "pieces root" is identical to the leaf hash.
        let file_root = leaf_hash.clone();

        // Note: While protocol-compliant small files don't have layers,
        // we keep this here to ensure the logic handles the presence of metadata.
        let mut layer_map = HashMap::new();
        layer_map.insert(
            file_root.clone(),
            serde_bencode::value::Value::Bytes(leaf_hash.clone()),
        );
        torrent.piece_layers = Some(serde_bencode::value::Value::Dict(layer_map));
        state.torrent = Some(torrent);

        // C. Init Piece Manager & Maps
        state.piece_manager.set_initial_fields(num_pieces, false);
        state
            .piece_manager
            .set_geometry(piece_len as u32, piece_len as u64, HashMap::new(), false);

        // Map Piece 0 -> File Root
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: piece_len as u64,
                root_hash: file_root.clone(),
                file_index: 0,
            }],
        );

        let peer_id = "priority_tester".to_string();
        add_peer(&mut state, &peer_id);

        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: data.clone(),
        });

        let verify_op = effects.iter().find_map(|e| {
            if let Effect::VerifyPieceV2 {
                root_hash, proof, ..
            } = e
            {
                Some((root_hash, proof))
            } else {
                None
            }
        });

        assert!(
            verify_op.is_some(),
            "Should trigger VerifyPieceV2 immediately via small file optimization"
        );

        let (target_hash, proof) = verify_op.unwrap();

        // The target_hash must be the file_root (which is the leaf_hash)
        assert_eq!(
            target_hash, &leaf_hash,
            "Verification hash mismatch. Expected the protocol-compliant file root."
        );

        assert!(
            proof.is_empty(),
            "Small files should verify directly without a Merkle proof."
        );
    }

    #[test]
    fn test_v2_tail_block_request_clamping() {
        use serde_bencode::value::Value;

        let piece_len = 16_384;
        let file_len: u64 = 20_000;
        let tail_size = 3_616;
        let num_pieces = 2;
        let padded_len = (num_pieces as u64) * (piece_len as u64); // 32,768

        let mut torrent = create_dummy_torrent(num_pieces);
        torrent.info.meta_version = Some(2);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.length = file_len as i64;
        torrent.info.pieces = Vec::new();

        let mut file_map = std::collections::HashMap::new();
        file_map.insert("length".as_bytes().to_vec(), Value::Int(file_len as i64));
        file_map.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(vec![0xAA; 32]),
        );
        let mut dir_map = std::collections::HashMap::new();
        dir_map.insert("".as_bytes().to_vec(), Value::Dict(file_map));
        let mut root_map = std::collections::HashMap::new();
        root_map.insert("test_tail_file".as_bytes().to_vec(), Value::Dict(dir_map));
        torrent.info.file_tree = Some(Value::Dict(root_map));

        let mut state = TorrentState::new(
            vec![0; 20],
            Some(torrent),
            Some(100),
            PieceManager::new(),
            HashMap::new(),
            false,
            None,
        );

        // This simulates exactly what TorrentState::new does incorrectly for V2.
        // The BlockManager now thinks the tail piece is full (16384 bytes).
        state.torrent_status = TorrentStatus::Standard;
        state.torrent_data_path = Some(std::path::PathBuf::from("/tmp/superseedr_test"));
        state.piece_manager.set_initial_fields(num_pieces, false);
        state
            .piece_manager
            .set_geometry(piece_len as u32, padded_len, HashMap::new(), false); // <--- CHANGED to padded_len
        state.piece_manager.need_queue = vec![1];

        let mut overrides = HashMap::new();
        overrides.insert(1, tail_size);
        state
            .piece_manager
            .set_geometry(piece_len as u32, padded_len, overrides, false);
        state.piece_manager.need_queue = vec![1];

        let peer_id = "strict_peer".to_string();
        let (tx, _rx) = tokio::sync::mpsc::channel(1);
        let mut peer = PeerState::new(peer_id.clone(), tx, state.now);
        peer.bitfield = vec![true, true];
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.am_interested = true;
        state.peers.insert(peer_id.clone(), peer);

        let effects = state.update(Action::AssignWork {
            peer_id: peer_id.clone(),
        });

        let mut request_found = false;
        for effect in effects {
            if let Effect::SendToPeer { cmd, .. } = effect {
                if let TorrentCommand::BulkRequest(reqs) = *cmd {
                    for (idx, _off, len) in reqs {
                        if idx == 1 {
                            request_found = true;
                            // Without the V2 map, this will be 16384 (Full Block) -> FAIL
                            assert_eq!(
                                len, tail_size,
                                "BUG REPRODUCED: Requested {} (full) instead of {} (tail). V2 roots missing.",
                                len, tail_size
                            );
                        }
                    }
                }
            }
        }

        if !request_found {
            panic!("Setup Failure: No requests generated.");
        }
    }

    #[test]
    fn test_v2_triggers_hash_request_when_buffering() {
        // 1. GIVEN: A pure V2 torrent state
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(1);
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new(); // Pure V2 (no V1 hashes)
        torrent.info.piece_length = 16384;

        // Setup State
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(16384, 16384, HashMap::new(), false);
        state.torrent_status = TorrentStatus::Standard;

        // Map piece 0 to a file larger than one piece to force buffering
        // (If file_len <= piece_len, it optimizes and verifies immediately)
        let root = vec![0xAA; 32];
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: 32768,
                root_hash: root.clone(),
                file_index: 0,
            }],
        );

        let peer_id = "v2_seeder".to_string();
        add_peer(&mut state, &peer_id);

        // 2. WHEN: We receive a block for this piece
        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0u8; 16384], // Full piece
        });

        // 3. THEN: The state should buffer the data AND request hashes

        // Assert buffering happened
        assert!(
            state.v2_pending_data.contains_key(&0),
            "Data should be buffered pending proof"
        );

        // Assert Effect was emitted
        let request_sent = effects.iter().any(|e| {
            matches!(e, Effect::RequestHashes { peer_id: id, piece_index: idx, .. }
                     if id == &peer_id && *idx == 0)
        });

        assert!(
            request_sent,
            "State failed to emit RequestHashes effect for buffered V2 data!"
        );
    }

    #[test]
    fn test_v2_magnet_scenario_requests_hashes_when_layers_missing() {
        // 1. SETUP: Create a "Magnet-like" Torrent state
        let mut state = create_empty_state();
        let piece_len = 16384;

        // Construct a Torrent that has Info (Roots) but NO Piece Layers
        let mut torrent = create_dummy_torrent(1);
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new(); // Pure v2
        torrent.info.piece_length = piece_len as i64;

        // CRITICAL: Ensure this is None. This simulates "Magnet Metadata Received".
        // Real .torrent files would populate this, but Magnet links don't give it to us.
        torrent.piece_layers = None;

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(1, false);
        state
            .piece_manager
            .set_geometry(piece_len as u32, piece_len as u64, HashMap::new(), false);
        state.torrent_status = TorrentStatus::Standard;

        // 2. SETUP ROOTS: Map piece 0 to a File Root
        // We use a file larger than piece_len (32KB) to force proof verification logic.
        let file_root = vec![0xAA; 32];
        let file_len = 32768;

        // In a real app, 'calculate_v2_mapping' populates this from the Info Dict.
        // Here we inject it manually to simulate that we know the Root.
        state.piece_to_roots.insert(
            0,
            vec![V2RootInfo {
                file_offset: 0,
                length: file_len,
                root_hash: file_root.clone(),
                file_index: 0,
            }],
        );

        let peer_id = "magnet_peer".to_string();
        add_peer(&mut state, &peer_id);

        // 3. EXECUTE: Peer sends us Data for Piece 0
        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: vec![0u8; 16384], // Full piece
        });

        // 4. VERIFY: The State must Buffer + Request Hashes
        // It cannot verify because 'piece_layers' is None, so it MUST ask the peer.

        // Check Buffering
        assert!(
            state.v2_pending_data.contains_key(&0),
            "Data should be buffered because we have no local proof"
        );

        // Check Effect
        let request_sent = effects.iter().any(|e| {
            if let Effect::RequestHashes {
                peer_id: pid,
                file_root: root,
                piece_index,
                ..
            } = e
            {
                // Verify we are asking the right peer for the right piece using the right root
                pid == &peer_id && piece_index == &0 && root == &file_root
            } else {
                false
            }
        });

        assert!(
            request_sent,
            "State failed to emit RequestHashes! It likely tried to verify locally and failed."
        );
    }

    #[test]
    fn test_state_v1_metadata_workflow() {
        use sha1::{Digest, Sha1};

        // 1. SETUP: Empty State
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/tmp/test_download"));
        let num_pieces = 100; // Standard V1 swarm
        let piece_len = 16384;

        // 2. CONSTRUCT V1 METADATA
        // V1 puts all hashes into a single byte string inside the Info Dict.
        let data_chunk = vec![0xAA; piece_len];
        let piece_hash = Sha1::digest(&data_chunk).to_vec();

        let mut all_hashes = Vec::new();
        for _ in 0..num_pieces {
            all_hashes.extend_from_slice(&piece_hash);
        }

        let mut torrent = create_dummy_torrent(0);
        torrent.info.meta_version = None; // V1
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = all_hashes; // <--- The V1 "Proof" is here immediately
        torrent.info.length = (num_pieces * piece_len) as i64;

        // 3. ACTION: METADATA RECEIVED
        state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 5000,
        });

        // CHECK: Bitfield resized correctly based on 'pieces' string length
        assert_eq!(state.piece_manager.bitfield.len(), num_pieces);
        assert_eq!(state.torrent_status, TorrentStatus::Validating);

        // 4. ACTION: VALIDATION COMPLETE
        state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });
        assert_eq!(state.torrent_status, TorrentStatus::Standard);

        // 5. EXECUTE DOWNLOAD (V1 Style)
        let peer_id = "v1_worker".to_string();
        add_peer(&mut state, &peer_id);

        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: data_chunk.clone(),
        });

        // CHECK: V1 Optimization
        // Unlike V2, we should NOT see 'RequestHashes'.
        // We SHOULD see 'VerifyPiece' immediately because we already have the hash.
        let verify_sent = effects
            .iter()
            .any(|e| matches!(e, Effect::VerifyPiece { piece_index: 0, .. }));
        assert!(
            verify_sent,
            "V1 failed to trigger immediate verification using info-dict hashes"
        );

        // Ensure no V2 requests leaked in
        let v2_request = effects
            .iter()
            .any(|e| matches!(e, Effect::RequestHashes { .. }));
        assert!(
            !v2_request,
            "V1 torrent incorrectly triggered V2 hash request"
        );
    }

    #[test]
    fn test_state_hybrid_metadata_workflow() {
        use serde_bencode::value::Value;
        use sha1::{Digest, Sha1};
        use std::collections::HashMap;

        let mut state = create_empty_state();
        let num_pieces = 50;
        let piece_len = 16384;

        // 1. CONSTRUCT HYBRID TORRENT
        // It has V1 'pieces' AND V2 'file_tree'
        let data_chunk = vec![0xBB; piece_len];
        let v1_hash = Sha1::digest(&data_chunk).to_vec();

        let mut v1_pieces = Vec::new();
        for _ in 0..num_pieces {
            v1_pieces.extend_from_slice(&v1_hash);
        }

        let mut torrent = create_dummy_torrent(0);
        torrent.info.meta_version = Some(2); // Hybrid implies v2 support
        torrent.info.piece_length = piece_len as i64;
        torrent.info.pieces = v1_pieces; // V1 Data

        // V2 Data (File Tree)
        let root_hash = vec![0xCC; 32];
        let total_len = (num_pieces * piece_len) as i64;

        let mut file_meta = HashMap::new();
        file_meta.insert("length".as_bytes().to_vec(), Value::Int(total_len));
        file_meta.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(root_hash.clone()),
        );

        let mut file_node = HashMap::new();
        file_node.insert("".as_bytes().to_vec(), Value::Dict(file_meta));

        let mut root_node = HashMap::new();
        root_node.insert("hybrid_file".as_bytes().to_vec(), Value::Dict(file_node));

        torrent.info.file_tree = Some(Value::Dict(root_node));

        // 2. ACTION: METADATA RECEIVED
        state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 9999,
        });
        state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });

        // 3. CHECK DUAL INITIALIZATION
        // V1 Check: Bitfield correct?
        assert_eq!(state.piece_manager.bitfield.len(), num_pieces);

        // V2 Check: Roots mapped?
        assert!(
            state.piece_to_roots.contains_key(&0),
            "Hybrid failed to map V2 roots"
        );
        assert!(
            state.piece_to_roots.contains_key(&(num_pieces as u32 - 1)),
            "Hybrid failed to map end piece"
        );

        // 4. EXECUTE DOWNLOAD
        let peer_id = "hybrid_worker".to_string();
        add_peer(&mut state, &peer_id);

        let effects = state.update(Action::IncomingBlock {
            peer_id: peer_id.clone(),
            piece_index: 0,
            block_offset: 0,
            data: data_chunk,
        });

        // 5. VERIFY HYBRID BEHAVIOR
        // It should prefer V1 verification (Immediate VerifyPiece) because it's faster
        // than asking for V2 proofs.
        let verify_v1 = effects
            .iter()
            .any(|e| matches!(e, Effect::VerifyPiece { piece_index: 0, .. }));
        assert!(verify_v1, "Hybrid failed to fallback to V1 verification");

        // It should NOT buffer/request V2 hashes if V1 verification is possible
        assert!(
            !state.v2_pending_data.contains_key(&0),
            "Hybrid inefficiently buffered data despite having V1 hashes"
        );
    }

    #[test]
    fn test_state_scale_1000_v2_metadata_workflow() {
        use serde_bencode::value::Value;
        use std::collections::HashMap; // Needed to construct the file tree

        // 1. SETUP: Empty State
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/tmp/test_download"));
        let num_pieces = 1000;
        let piece_len = 1024;
        let total_len = (num_pieces as u64) * (piece_len as u64);
        let root_hash = vec![0xAA; 32];

        // 2. CONSTRUCT METADATA (Simulate Magnet Link Download)
        // We start with a Torrent that has NO layers and NO pieces, just the File Tree.
        let mut torrent = create_dummy_torrent(0);
        torrent.info.piece_length = piece_len as i64;
        torrent.info.meta_version = Some(2);
        torrent.info.pieces = Vec::new(); // Pure V2
        torrent.piece_layers = None; // <--- Crucial: Forces proof requests

        // Construct V2 File Tree: { "big_file": { "": { "length": ..., "pieces root": ... } } }
        // This is what the State uses to populate 'piece_to_roots' during MetadataReceived
        let mut file_meta = HashMap::new();
        file_meta.insert("length".as_bytes().to_vec(), Value::Int(total_len as i64));
        file_meta.insert(
            "pieces root".as_bytes().to_vec(),
            Value::Bytes(root_hash.clone()),
        );

        let mut file_node = HashMap::new();
        file_node.insert("".as_bytes().to_vec(), Value::Dict(file_meta));

        let mut root_node = HashMap::new();
        root_node.insert("big_file".as_bytes().to_vec(), Value::Dict(file_node));

        torrent.info.file_tree = Some(Value::Dict(root_node));

        // 3. ACTION: METADATA RECEIVED
        let _meta_effects = state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 12345,
        });

        // CHECK: State successfully mapped the file tree to pieces
        assert_eq!(state.torrent_status, TorrentStatus::Validating);
        // The file is 1000 pieces long, so piece 0 and piece 999 must exist in the map
        assert!(
            state.piece_to_roots.contains_key(&0),
            "Failed to map piece 0 from file tree"
        );
        assert!(
            state.piece_to_roots.contains_key(&999),
            "Failed to map piece 999 from file tree"
        );
        assert_eq!(
            state.piece_manager.bitfield.len(),
            1000,
            "Incorrect piece count calculated"
        );

        // 4. ACTION: VALIDATION COMPLETE
        // We must exit the 'Validating' state to accept incoming blocks
        state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });
        assert_eq!(state.torrent_status, TorrentStatus::Standard);

        // 5. EXECUTE SCALE LOOP (1000 Blocks)
        let peer_id = "v2_full_worker".to_string();
        add_peer(&mut state, &peer_id);

        let data_chunk = vec![0u8; piece_len as usize];
        let proof_chunk = vec![0xFF; 32];

        for i in 0..num_pieces {
            let piece_idx = i as u32;

            // A. Incoming Block
            let data_effects = state.update(Action::IncomingBlock {
                peer_id: peer_id.clone(),
                piece_index: piece_idx,
                block_offset: 0,
                data: data_chunk.clone(),
            });

            // CHECK: Buffer + Request Effect
            assert!(
                state.v2_pending_data.contains_key(&piece_idx),
                "Piece {} not buffered",
                piece_idx
            );

            let request_correct = data_effects.iter().any(|e| {
                // Ensure the Effect carries the Root Hash derived from our File Tree
                matches!(e, Effect::RequestHashes { file_root, piece_index, .. }
                         if *piece_index == piece_idx && file_root == &root_hash)
            });
            assert!(
                request_correct,
                "Piece {} failed to emit RequestHashes with correct Root",
                piece_idx
            );

            // B. Proof Received
            let proof_effects = state.update(Action::MerkleProofReceived {
                peer_id: peer_id.clone(),
                piece_index: piece_idx,
                proof: proof_chunk.clone(),
            });

            // CHECK: Verify Effect + Buffer Clear
            let verify_triggered = proof_effects.iter().any(|e| {
                matches!(e, Effect::VerifyPieceV2 { piece_index, .. } if *piece_index == piece_idx)
            });
            assert!(
                verify_triggered,
                "Piece {} failed to verify after proof",
                piece_idx
            );
            assert!(
                !state.v2_pending_data.contains_key(&piece_idx),
                "Buffer leak for piece {}",
                piece_idx
            );
        }

        // 6. FINAL CLEANUP CHECK
        assert!(state.v2_pending_data.is_empty());
    }

    #[test]
    fn test_repro_magnet_bitfield_truncation() {
        // GIVEN: A state initialized like a Magnet link (No metadata, 0 pieces known)
        let mut state = create_empty_state();
        state.torrent = None;
        state.torrent_status = TorrentStatus::AwaitingMetadata;
        // Explicitly set piece manager to 0 to mimic "don't know size yet"
        state.piece_manager.set_initial_fields(0, false);

        let peer_id = "magnet_seeder".to_string();
        add_peer(&mut state, &peer_id);

        // WHEN: Peer sends a Bitfield BEFORE we have metadata
        // Scenario: 8 pieces, peer has all of them (0xFF = 11111111)
        state.update(Action::PeerBitfieldReceived {
            peer_id: peer_id.clone(),
            bitfield: vec![0xFF],
        });

        // CHECK 1: The peer's bitfield should NOT be truncated to 0.
        // It should hold the raw bits until we know better.
        let peer_pre = state.peers.get(&peer_id).unwrap();
        assert!(
            !peer_pre.bitfield.is_empty(),
            "BUG REPRODUCED: Peer bitfield was truncated/wiped because we had 0 pieces!"
        );

        // WHEN: Metadata finally arrives (defining 8 pieces)
        let mut torrent = create_dummy_torrent(8);
        torrent.info.piece_length = 16384;
        torrent.info.length = 16384 * 8;

        state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 123,
        });

        // CRITICAL STEP: MetadataReceived puts us in 'Validating'.
        // AssignWork ignores everything during 'Validating'.
        // We must complete validation to enter 'Standard' mode and calculate interest.
        state.update(Action::ValidationComplete {
            completed_pieces: vec![], // We found nothing locally
        });

        // THEN: The peer should still be seen as a Seeder (having all pieces)
        let peer_post = state.peers.get(&peer_id).unwrap();

        assert_eq!(
            peer_post.bitfield.len(),
            8,
            "Bitfield should be resized to correct piece count"
        );
        assert!(
            peer_post.bitfield.iter().all(|&b| b),
            "Peer data lost! Expected all TRUE, got {:?}",
            peer_post.bitfield
        );

        // Final sanity check: Manager should be interested
        state.update(Action::AssignWork {
            peer_id: peer_id.clone(),
        });
        let peer_final = state.peers.get(&peer_id).unwrap();

        assert!(
            peer_final.am_interested,
            "We should be interested in the seeder (failed if bitfield was wiped)"
        );
    }

    #[test]
    fn test_assign_work_is_blocked_when_path_is_missing() {
        // 1. GIVEN: A torrent state with metadata but NO download path
        let mut state = create_empty_state();
        let num_pieces = 5;
        let torrent = create_dummy_torrent(num_pieces);

        // Set metadata as if it just arrived from a peer
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(num_pieces, false);
        state.piece_manager.block_manager.set_geometry(
            16384,
            (16384 * num_pieces) as u64,
            vec![],
            vec![],
            HashMap::new(),
            false,
        );

        // Status moves to Standard/Endgame normally after metadata hydration
        state.torrent_status = TorrentStatus::Standard;
        state.piece_manager.need_queue = (0..num_pieces as u32).collect();

        // CRITICAL: Ensure path is None (User is still in File Browser)
        state.torrent_data_path = None;

        // 2. GIVEN: A connected, unchoked peer who has all pieces
        let peer_id = "seeder_peer".to_string();
        add_peer(&mut state, &peer_id);
        let peer = state.peers.get_mut(&peer_id).unwrap();
        peer.peer_choking = ChokeStatus::Unchoke;
        peer.bitfield = vec![true; num_pieces];

        // 3. WHEN: We try to assign work
        let effects = state.update(Action::AssignWork {
            peer_id: peer_id.clone(),
        });

        // 4. THEN: No requests should be generated
        let has_requests = effects.iter().any(|e| {
            matches!(e, Effect::SendToPeer { cmd, .. }
                if matches!(**cmd, TorrentCommand::BulkRequest(_)))
        });

        assert!(
            !has_requests,
            "PROTOCOL ERROR: Engine requested blocks before a download path was selected!"
        );
        assert!(
            state.peers[&peer_id].pending_requests.is_empty(),
            "Peer should have 0 pending requests when path is missing"
        );
    }

    #[test]
    fn test_delete_action_without_path_emits_completion() {
        // 1. GIVEN: A state with metadata but NO torrent_data_path or multi_file_info
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(5);
        let info_hash = state.info_hash.clone();

        state.torrent = Some(torrent);
        state.torrent_data_path = None;
        state.multi_file_info = None;
        // status will be Validating because torrent is Some
        state.torrent_status = TorrentStatus::Validating;

        // 2. WHEN: Action::Delete is triggered
        let effects = state.update(Action::Delete);

        // 3. THEN: It should NOT emit Effect::DeleteFiles
        let has_delete_files = effects
            .iter()
            .any(|e| matches!(e, Effect::DeleteFiles { .. }));
        assert!(
            !has_delete_files,
            "Should not attempt to delete files when path is missing"
        );

        // 4. THEN: It SHOULD emit Effect::EmitManagerEvent(ManagerEvent::DeletionComplete)
        let completion_event = effects.iter().find(|e| {
            if let Effect::EmitManagerEvent(ManagerEvent::DeletionComplete(hash, result)) = e {
                return hash == &info_hash && result.is_ok();
            }
            false
        });

        assert!(
            completion_event.is_some(),
            "Manager must emit DeletionComplete(Ok) to notify the app to remove the UI entry"
        );

        // 5. THEN: Internal state should be reset correctly
        assert!(state.is_paused);
        assert_eq!(state.torrent_status, TorrentStatus::Validating);
        assert_eq!(state.last_activity, TorrentActivity::Initializing);
    }

    #[test]
    fn test_file_priority_boundary_mapping() {
        // GIVEN: A torrent with 3 pieces (size 10).
        // File A: Size 15 (Spans Piece 0 and half of Piece 1) -> Set to SKIP
        // File B: Size 15 (Spans rest of Piece 1 and Piece 2) -> Set to NORMAL

        let mut state = create_empty_state();
        let piece_len = 10;

        let mut torrent = create_dummy_torrent(3);
        torrent.info.piece_length = piece_len;
        torrent.info.length = 30;
        torrent.info.files = vec![
            crate::torrent_file::InfoFile {
                length: 15,
                path: vec!["A".into()],
                md5sum: None,
                attr: None,
            },
            crate::torrent_file::InfoFile {
                length: 15,
                path: vec!["B".into()],
                md5sum: None,
                attr: None,
            },
        ];

        state.torrent = Some(torrent);
        // Init bitfield so length check passes
        state.piece_manager.set_initial_fields(3, false);

        // WHEN: We set priorities
        let mut priorities = HashMap::new();
        priorities.insert(0, FilePriority::Skip); // File A
        priorities.insert(1, FilePriority::Normal); // File B

        let vec = state.calculate_piece_priorities(&priorities);

        // THEN:
        // Piece 0 (0-10): Only File A (Skip) -> SKIP
        assert_eq!(vec[0], EffectivePiecePriority::Skip);

        // Piece 1 (10-20): File A (Skip) AND File B (Normal) -> NORMAL (Boundary protection)
        assert_eq!(vec[1], EffectivePiecePriority::Normal);

        // Piece 2 (20-30): Only File B (Normal) -> NORMAL
        assert_eq!(vec[2], EffectivePiecePriority::Normal);
    }

    #[test]
    fn test_completion_with_skipped_files() {
        // GIVEN: A torrent with 2 pieces.
        // Piece 0: Skipped
        // Piece 1: Done
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;

        // Mock the PieceManager state
        state.piece_manager.set_initial_fields(2, false);
        state.piece_manager.bitfield[1] = PieceStatus::Done;

        // Apply Priorities: 0=Skip, 1=Normal
        state.piece_manager.apply_priorities(vec![
            EffectivePiecePriority::Skip,
            EffectivePiecePriority::Normal,
        ]);

        // WHEN: We check completion
        // Note: queues must be empty for CheckCompletion to succeed
        state.piece_manager.need_queue.clear();
        state.piece_manager.pending_queue.clear();

        let effects = state.update(Action::CheckCompletion);

        // THEN: The torrent should be considered DONE
        assert_eq!(state.torrent_status, TorrentStatus::Done);

        // BUT: It should NOT report "Completed" to the tracker (physically incomplete)
        let sent_completed_event = effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceCompleted { .. }));
        assert!(
            !sent_completed_event,
            "Should NOT send 'completed' event if files were skipped"
        );
    }

    #[test]
    fn test_repro_validation_complete_ignores_skip_mixed() {
        let mut state = create_empty_state();
        let piece_len = 10; // Tiny pieces for easy math

        // 1. Construct Multi-File Torrent (File A=Piece 0, File B=Piece 1)
        let mut torrent = create_dummy_torrent(2);
        torrent.info.piece_length = piece_len;
        torrent.info.length = 0; // Standard for multi-file is 0 or sum
        torrent.info.files = vec![
            crate::torrent_file::InfoFile {
                length: piece_len, // 10 bytes (Piece 0)
                path: vec!["A.txt".into()],
                md5sum: None,
                attr: None,
            },
            crate::torrent_file::InfoFile {
                length: piece_len, // 10 bytes (Piece 1)
                path: vec!["B.txt".into()],
                md5sum: None,
                attr: None,
            },
        ];

        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);

        // 2. Set Priorities: File 0 (A) -> SKIP
        let mut priorities = HashMap::new();
        priorities.insert(0, FilePriority::Skip);
        // File 1 (B) defaults to Normal

        let prio_vec = state.calculate_piece_priorities(&priorities);
        state.piece_manager.apply_priorities(prio_vec);

        // Pre-condition: Need queue should ONLY have Piece 1
        // Piece 0 should be skipped.
        assert_eq!(
            state.piece_manager.need_queue,
            vec![1],
            "Setup failed: Queue should contain only piece 1"
        );

        // 3. Trigger Validation Complete
        state.torrent_status = TorrentStatus::Validating;

        // WHEN: ValidationComplete runs (finding nothing)
        state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });

        // THEN: The Need Queue should STILL not contain Piece 0.
        // If the bug exists, Piece 0 will be re-added here.
        assert!(
            !state.piece_manager.need_queue.contains(&0),
            "REGRESSION: Skipped piece 0 was added back to queue! Queue: {:?}",
            state.piece_manager.need_queue
        );

        // Verify Piece 1 is still there
        assert!(
            state.piece_manager.need_queue.contains(&1),
            "Piece 1 should still be needed"
        );
    }

    #[test]
    fn test_config_after_metadata_applies_priorities() {
        // GIVEN: A state that already has metadata (defaulting to Download All)
        let mut state = create_empty_state();
        let torrent = create_dummy_torrent(2); // 2 pieces
        state.torrent = Some(torrent);
        state.piece_manager.set_initial_fields(2, false);

        // Initial check: Need queue full
        assert_eq!(state.piece_manager.need_queue.len(), 2);

        // WHEN: User config arrives LATER, setting everything to SKIP
        let mut priorities = HashMap::new();
        priorities.insert(0, FilePriority::Skip); // File 0 (covers piece 0/1 in dummy torrent)

        let effects = state.update(Action::SetUserTorrentConfig {
            torrent_data_path: PathBuf::from("/tmp"),
            file_priorities: priorities,
            container_name: None,
        });

        // THEN 1: Priorities applied immediately (Queue Cleared)
        assert!(
            state.piece_manager.need_queue.is_empty(),
            "SetUserTorrentConfig failed to update PieceManager queues!"
        );

        // THEN 2: Validation Started (Because storage wasn't init yet)
        assert_eq!(state.torrent_status, TorrentStatus::Validating);
        assert!(effects.iter().any(|e| matches!(e, Effect::StartValidation)));

        // WHEN: Validation finishes (finding nothing on disk)
        let completion_effects = state.update(Action::ValidationComplete {
            completed_pieces: vec![],
        });

        // THEN 3: Status transitions to Done
        assert_eq!(state.torrent_status, TorrentStatus::Done);

        // Verify we told the tracker we are complete
        let _sent_completed = completion_effects
            .iter()
            .any(|e| matches!(e, Effect::AnnounceCompleted { .. }));
        // Note: physically_complete is False (0 bytes on disk), so AnnounceCompleted might NOT send depending on logic.
        // But the status MUST be Done.
    }

    #[test]
    fn test_peer_disconnect_batches_until_threshold() {
        let mut state = create_empty_state();
        state.torrent_status = TorrentStatus::Standard;
        let disconnect_batch_threshold = 50;

        // Add threshold + 1 peers to ensure we cross the threshold exactly once.
        for i in 0..(disconnect_batch_threshold + 1) {
            let pid = format!("peer_{}", i);
            add_peer(&mut state, &pid);

            let effects = state.update(Action::PeerDisconnected {
                peer_id: pid.clone(),
                force: false,
            });

            if i < disconnect_batch_threshold - 1 {
                // Should not have processed yet
                assert!(effects.is_empty() || matches!(effects[0], Effect::DoNothing));
                assert_eq!(state.pending_disconnects.len(), i + 1);
            } else if i == disconnect_batch_threshold - 1 {
                // On the threshold peer, it should flush that full batch.
                assert_eq!(effects.len(), disconnect_batch_threshold * 2);
                assert!(state.pending_disconnects.is_empty());
            }
        }

        // The final peer should now be sitting alone in the new batch.
        assert_eq!(state.pending_disconnects.len(), 1);
    }

    #[test]
    fn test_peer_disconnect_force_flush() {
        let mut state = create_empty_state();

        // Add only 5 peers (well below the batch threshold)
        for i in 0..5 {
            let pid = format!("peer_{}", i);
            add_peer(&mut state, &pid);
            state.update(Action::PeerDisconnected {
                peer_id: pid,
                force: false,
            });
        }

        assert_eq!(state.pending_disconnects.len(), 5);

        // Trigger a forced flush (passing an empty ID as Cleanup would)
        let effects = state.update(Action::PeerDisconnected {
            peer_id: String::new(),
            force: true,
        });

        // Check that all 5 were processed
        assert_eq!(effects.len(), 10); // 5 Disconnects + 5 Events
        assert!(state.pending_disconnects.is_empty());
        assert_eq!(state.peers.len(), 0);
    }

    #[test]
    fn test_cleanup_flushes_stuck_peers_via_batch() {
        let mut state = create_empty_state();
        state.now = Instant::now();

        // Add a "stuck" peer (empty peer_id, created 10 seconds ago)
        let (tx, _) = tokio::sync::mpsc::channel(1);
        let mut peer = PeerState::new(
            "127.0.0.1:1234".to_string(),
            tx,
            state.now - Duration::from_secs(10),
        );
        peer.peer_id = Vec::new(); // Empty ID = Stuck
        state.peers.insert("127.0.0.1:1234".to_string(), peer);

        // Run Cleanup
        let effects = state.update(Action::Cleanup);

        // Verify the peer was removed via the batching logic called by Cleanup
        assert!(state.peers.is_empty());
        assert!(effects
            .iter()
            .any(|e| matches!(e, Effect::DisconnectPeer { .. })));
        assert!(effects.iter().any(|e| matches!(
            e,
            Effect::EmitManagerEvent(ManagerEvent::PeerDisconnected { .. })
        )));
    }

    #[test]
    fn touched_relative_paths_for_activity_handles_single_file() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/downloads"));
        state.torrent = Some(Torrent {
            info: crate::torrent_file::Info {
                piece_length: 100,
                ..Default::default()
            },
            ..Default::default()
        });
        state.multi_file_info = Some(MultiFileInfo {
            files: vec![crate::storage::FileInfo {
                path: PathBuf::from("sample.bin"),
                length: 100,
                global_start_offset: 0,
                is_padding: false,
                is_skipped: false,
            }],
            total_size: 100,
        });

        assert_eq!(
            drained_download_paths_for_activity(&mut state, 0, 0, 10),
            vec!["sample.bin".to_string()]
        );
        assert_eq!(
            drained_download_paths_for_activity(&mut state, 0, 90, 10),
            vec!["sample.bin".to_string()]
        );
        assert!(drained_download_paths_for_activity(&mut state, 0, 0, 0).is_empty());
    }

    #[test]
    fn touched_relative_paths_for_activity_handles_boundary_spans() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/downloads"));
        state.torrent = Some(Torrent {
            info: crate::torrent_file::Info {
                piece_length: 100,
                ..Default::default()
            },
            ..Default::default()
        });
        state.multi_file_info = Some(MultiFileInfo {
            files: vec![
                crate::storage::FileInfo {
                    path: PathBuf::from("one.bin"),
                    length: 50,
                    global_start_offset: 0,
                    is_padding: false,
                    is_skipped: false,
                },
                crate::storage::FileInfo {
                    path: PathBuf::from("two.bin"),
                    length: 70,
                    global_start_offset: 50,
                    is_padding: false,
                    is_skipped: false,
                },
            ],
            total_size: 120,
        });

        assert_eq!(
            drained_download_paths_for_activity(&mut state, 0, 40, 30),
            vec!["one.bin".to_string(), "two.bin".to_string()]
        );
        assert_eq!(
            drained_download_paths_for_activity(&mut state, 0, 50, 10),
            vec!["two.bin".to_string()]
        );
    }

    #[test]
    fn incoming_block_queues_file_activity_updates_until_tick_flush() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/downloads"));
        state.torrent = Some(Torrent {
            info: crate::torrent_file::Info {
                piece_length: 100,
                pieces: vec![0u8; 20],
                length: 120,
                ..Default::default()
            },
            ..Default::default()
        });
        state.piece_manager.bitfield = vec![PieceStatus::Need];
        state.multi_file_info = Some(MultiFileInfo {
            files: vec![
                crate::storage::FileInfo {
                    path: PathBuf::from("one.bin"),
                    length: 50,
                    global_start_offset: 0,
                    is_padding: false,
                    is_skipped: false,
                },
                crate::storage::FileInfo {
                    path: PathBuf::from("two.bin"),
                    length: 70,
                    global_start_offset: 50,
                    is_padding: false,
                    is_skipped: false,
                },
            ],
            total_size: 120,
        });

        let effects = state.update(Action::IncomingBlock {
            peer_id: "peer_a".to_string(),
            piece_index: 0,
            block_offset: 40,
            data: vec![1; 30],
        });

        assert!(effects.iter().any(|effect| matches!(
            effect,
            Effect::EmitManagerEvent(ManagerEvent::BlockReceived { .. })
        )));

        let updates = state.drain_file_activity_updates();
        assert_eq!(updates.len(), 1);
        let update = &updates[0];
        assert_eq!(
            update.touched_relative_paths,
            vec!["one.bin".to_string(), "two.bin".to_string()]
        );
        assert_eq!(update.direction, FileActivityDirection::Download);
        assert!(state.drain_file_activity_updates().is_empty());
    }

    #[test]
    fn drain_file_activity_updates_dedupes_paths_within_each_direction() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/downloads"));
        state.torrent = Some(Torrent {
            info: crate::torrent_file::Info {
                piece_length: 100,
                pieces: vec![0u8; 20],
                length: 120,
                ..Default::default()
            },
            ..Default::default()
        });
        state.multi_file_info = Some(MultiFileInfo {
            files: vec![
                crate::storage::FileInfo {
                    path: PathBuf::from("one.bin"),
                    length: 50,
                    global_start_offset: 0,
                    is_padding: false,
                    is_skipped: false,
                },
                crate::storage::FileInfo {
                    path: PathBuf::from("two.bin"),
                    length: 70,
                    global_start_offset: 50,
                    is_padding: false,
                    is_skipped: false,
                },
            ],
            total_size: 120,
        });

        state.record_pending_file_activity(0, 0, 10, FileActivityDirection::Download);
        state.record_pending_file_activity(0, 20, 10, FileActivityDirection::Download);
        state.record_pending_file_activity(0, 60, 10, FileActivityDirection::Upload);

        let updates = state.drain_file_activity_updates();
        assert_eq!(updates.len(), 2);

        let mut saw_download = false;
        let mut saw_upload = false;

        for update in updates {
            match update.direction {
                FileActivityDirection::Download => {
                    saw_download = true;
                    assert_eq!(update.touched_relative_paths, vec!["one.bin".to_string()]);
                }
                FileActivityDirection::Upload => {
                    saw_upload = true;
                    assert_eq!(update.touched_relative_paths, vec!["two.bin".to_string()]);
                }
            }
        }

        assert!(saw_download);
        assert!(saw_upload);
    }

    #[test]
    fn drain_file_activity_updates_preserves_out_of_order_intervals() {
        let mut state = create_empty_state();
        state.torrent_data_path = Some(PathBuf::from("/downloads"));
        state.torrent = Some(Torrent {
            info: crate::torrent_file::Info {
                piece_length: 100,
                pieces: vec![0u8; 20],
                length: 120,
                ..Default::default()
            },
            ..Default::default()
        });
        state.multi_file_info = Some(MultiFileInfo {
            files: vec![
                crate::storage::FileInfo {
                    path: PathBuf::from("one.bin"),
                    length: 50,
                    global_start_offset: 0,
                    is_padding: false,
                    is_skipped: false,
                },
                crate::storage::FileInfo {
                    path: PathBuf::from("two.bin"),
                    length: 70,
                    global_start_offset: 50,
                    is_padding: false,
                    is_skipped: false,
                },
            ],
            total_size: 120,
        });

        state.record_pending_file_activity(0, 60, 10, FileActivityDirection::Download);
        state.record_pending_file_activity(0, 0, 10, FileActivityDirection::Download);

        let updates = state.drain_file_activity_updates();
        assert_eq!(updates.len(), 1);
        assert_eq!(
            updates[0].touched_relative_paths,
            vec!["one.bin".to_string(), "two.bin".to_string()]
        );
        assert_eq!(updates[0].direction, FileActivityDirection::Download);
    }

    #[test]
    fn test_container_logic_explicit_no_folder() {
        let mut state = create_empty_state();
        let mut torrent = create_dummy_torrent(2);

        // Setup: Make it a Multi-File Torrent
        torrent.info.name = "MyTorrent".to_string();
        torrent.info.files = vec![
            crate::torrent_file::InfoFile {
                length: 100,
                path: vec!["file_a.txt".to_string()],
                md5sum: None,
                attr: None,
            },
            crate::torrent_file::InfoFile {
                length: 100,
                path: vec!["file_b.txt".to_string()],
                md5sum: None,
                attr: None,
            },
        ];

        state.torrent = Some(torrent);
        state.torrent_data_path = Some(PathBuf::from("/tmp/downloads"));

        // ACTION: User explicitly selected "No Folder" (Empty String)
        state.container_name = Some("".to_string());

        state.rebuild_multi_file_info();

        // ASSERTION: Paths should be relative to root, not /tmp/downloads/MyTorrent/
        let mfi = state.multi_file_info.as_ref().expect("MFI should be built");

        // Expected: /tmp/downloads/file_a.txt
        let expected_path = PathBuf::from("/tmp/downloads/file_a.txt");
        assert_eq!(
            mfi.files[0].path, expected_path,
            "Should flatten multi-file torrent when container_name is empty"
        );
    }
}

#[cfg(test)]
mod deletion_tests {
    use super::*;
    use crate::storage::{FileInfo, MultiFileInfo};
    use std::path::PathBuf;

    // Helper to mock MFI
    fn mock_mfi(paths: Vec<&str>) -> MultiFileInfo {
        let files = paths
            .into_iter()
            .map(|p| FileInfo {
                path: PathBuf::from(p),
                length: 100,
                global_start_offset: 0,
                is_padding: false,
                is_skipped: false,
            })
            .collect();

        MultiFileInfo {
            files,
            total_size: 100,
        }
    }

    #[test]
    fn test_delete_single_file_torrent() {
        let base = PathBuf::from("/Downloads");
        // Case: Torrent is just "linux.iso" directly in Downloads
        let mfi = mock_mfi(vec!["/Downloads/linux.iso"]);

        let (files, dirs) = calculate_deletion_lists(&mfi, &base, None);

        assert_eq!(files.len(), 1);
        assert_eq!(files[0], PathBuf::from("/Downloads/linux.iso"));

        // Critical: Should NOT delete /Downloads
        assert!(
            dirs.is_empty(),
            "Single file torrent should not delete root dir"
        );
    }

    #[test]
    fn test_delete_standard_folder_torrent() {
        let base = PathBuf::from("/Downloads");
        // Case: "Album Name/01.mp3"
        let mfi = mock_mfi(vec!["/Downloads/Album/01.mp3", "/Downloads/Album/02.mp3"]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, None);

        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0], PathBuf::from("/Downloads/Album"));
    }

    #[test]
    fn test_delete_nested_directories() {
        let base = PathBuf::from("/Downloads");
        // Case: "Game/Data/Textures/skin.png"
        let mfi = mock_mfi(vec![
            "/Downloads/Game/readme.txt",
            "/Downloads/Game/Data/config.ini",
            "/Downloads/Game/Data/Textures/skin.png",
        ]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, None);

        // Should identify: Game, Game/Data, Game/Data/Textures
        assert_eq!(dirs.len(), 3);

        // Verify Sort Order (Deepest First)
        assert_eq!(dirs[0], PathBuf::from("/Downloads/Game/Data/Textures"));
        assert_eq!(dirs[1], PathBuf::from("/Downloads/Game/Data"));
        assert_eq!(dirs[2], PathBuf::from("/Downloads/Game"));
    }

    #[test]
    fn test_delete_safety_boundary_escape() {
        let base = PathBuf::from("/Downloads");

        // Edge Case: File path somehow points outside base (e.g. config error)
        let mfi = mock_mfi(vec!["/System/Critical/boot.ini"]);

        let (files, dirs) = calculate_deletion_lists(&mfi, &base, None);

        // We still delete the file (it belongs to the torrent),
        // but we MUST NOT delete parent folders up to root if they aren't in base.
        assert_eq!(files.len(), 1);
        assert!(
            dirs.is_empty(),
            "Should not identify directories outside base path"
        );
    }

    #[test]
    fn test_delete_matching_container() {
        // Scenario: Container "LinuxDistro" matches torrent name "LinuxDistro"
        let base = PathBuf::from("/Downloads/LinuxDistro");
        let name = "LinuxDistro";
        let mfi = mock_mfi(vec!["/Downloads/LinuxDistro/image.iso"]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, Some(name));

        // Should include base path because names match
        assert!(
            dirs.contains(&base),
            "Should delete container if name matches"
        );
    }

    #[test]
    fn test_delete_root_safety_mismatch() {
        // Scenario: Saved directly to "Downloads" (No Container)
        let base = PathBuf::from("/Downloads");
        let name = "LinuxDistro";
        let mfi = mock_mfi(vec!["/Downloads/image.iso"]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, Some(name));

        // "Downloads" != "LinuxDistro" -> Do NOT delete base
        assert!(
            dirs.is_empty(),
            "Should NOT delete root folder if names mismatch"
        );
    }

    #[test]
    fn test_delete_renamed_container_safety() {
        // Scenario: User renamed "LinuxDistro" to "MyStuff"
        let base = PathBuf::from("/Downloads/MyStuff");
        let name = "LinuxDistro";
        let mfi = mock_mfi(vec!["/Downloads/MyStuff/image.iso"]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, Some(name));

        // "MyStuff" != "LinuxDistro" -> Safe fallback is to KEEP the folder
        assert!(
            dirs.is_empty(),
            "Should preserve renamed container for safety"
        );
    }

    #[test]
    fn test_delete_subfolders_always() {
        // Scenario: Torrent has internal folders. Even if root is safe, subfolders must go.
        // Base: /Downloads (Safe)
        // File: /Downloads/Album/song.mp3
        let base = PathBuf::from("/Downloads");
        let name = "Album";
        let mfi = mock_mfi(vec!["/Downloads/Album/song.mp3"]);

        let (_, dirs) = calculate_deletion_lists(&mfi, &base, Some(name));

        // Should delete "Album" (child) but NOT "Downloads" (base)
        assert_eq!(dirs.len(), 1);
        assert_eq!(dirs[0], PathBuf::from("/Downloads/Album"));
    }
}

#[cfg(test)]
fn check_invariants(state: &TorrentState) {
    // CATEGORY 1: Data Consistency (The "Is the Math Right?" Check)

    // The global session total MUST be >= the sum of currently connected peers.
    // (It is not == because disconnected peers contribute to the total but are gone from the map).
    let sum_peer_dl: u64 = state.peers.values().map(|p| p.total_bytes_downloaded).sum();
    let sum_peer_ul: u64 = state.peers.values().map(|p| p.total_bytes_uploaded).sum();

    assert!(
        state.session_total_downloaded >= sum_peer_dl,
        "Global DL ({}) < Sum of Peers ({}) - Data created from thin air!",
        state.session_total_downloaded,
        sum_peer_dl
    );

    assert!(
        state.session_total_uploaded >= sum_peer_ul,
        "Global UL ({}) < Sum of Peers ({}) - Data created from thin air!",
        state.session_total_uploaded,
        sum_peer_ul
    );

    if let Some(torrent) = &state.torrent {
        let expected_pieces = torrent.info.pieces.len() / 20;
        assert_eq!(
            state.piece_manager.bitfield.len(),
            expected_pieces,
            "Bitfield length mismatch! Expected {}, Got {}",
            expected_pieces,
            state.piece_manager.bitfield.len()
        );

        // Check peer bitfield safety
        for (id, peer) in &state.peers {
            if !peer.bitfield.is_empty() {
                assert_eq!(
                    peer.bitfield.len(),
                    expected_pieces,
                    "Peer {} bitfield len mismatch. Vulnerable to panic.",
                    id
                );
            }
        }
    }

    // CATEGORY 2: Queue Synchronization (The "Ghost Piece" Check)

    // If a piece is in `pending_queue` (Global), AT LEAST one peer must be working on it.
    for &piece_idx in state.piece_manager.pending_queue.keys() {
        let exists_in_peer = state
            .peers
            .values()
            .any(|p| p.pending_requests.contains(&piece_idx));
        assert!(
            exists_in_peer,
            "Piece {} is globally Pending but NO peer has it. Download is stalled!",
            piece_idx
        );
    }

    // If a peer has a pending request, that piece MUST be globally Pending (or Done).
    // It cannot be in the "Need" queue.
    for (id, peer) in &state.peers {
        for &req in &peer.pending_requests {
            let in_need = state.piece_manager.need_queue.contains(&req);

            // It's okay if it's Done (race condition where write finished but peer not updated yet)
            // But it is NEVER okay to be in the Need queue while a peer thinks they are downloading it.
            assert!(
                !in_need,
                "Peer {} is downloading Piece {}, but Manager thinks it is still Needed!",
                id, req
            );
        }
    }

    for piece in &state.piece_manager.need_queue {
        assert!(
            !state.piece_manager.pending_queue.contains_key(piece),
            "Piece {} is in both Need and Pending queues!",
            piece
        );
    }

    // CATEGORY 3: State Machine Logic

    match state.torrent_status {
        TorrentStatus::Done => {
            // If Done, we should need nothing.
            assert!(
                state.piece_manager.need_queue.is_empty(),
                "Status is Done but Need queue has items!"
            );
            assert!(
                state.piece_manager.pending_queue.is_empty(),
                "Status is Done but Pending queue has items!"
            );

            // If Done, we should not be Interested in anyone.
            let am_interested = state.peers.values().any(|p| p.am_interested);
            assert!(
                !am_interested,
                "Status is Done but we are still Interested in peers!"
            );
        }
        TorrentStatus::Endgame => {
            // Endgame means Need is empty, but Pending is NOT.
            assert!(
                state.piece_manager.need_queue.is_empty(),
                "Status is Endgame but Need queue is not empty!"
            );
            // Pending might be empty if the last piece just finished but status hasn't transitioned yet,
            // but typically it should have items.
        }
        TorrentStatus::Standard => {}
        TorrentStatus::Validating => {}
        TorrentStatus::AwaitingMetadata => {}
    }

    // CATEGORY 4: Resource & Math Integrity

    for (key, peer) in &state.peers {
        assert_eq!(
            key, &peer.ip_port,
            "Peer Map Key '{}' does not match struct IP '{}'",
            key, peer.ip_port
        );
    }

    assert_eq!(
        state.number_of_successfully_connected_peers,
        state.peers.len(),
        "Peer count metric out of sync with Map size!"
    );

    if state.torrent.is_some() {
        // Count how many pieces in the bitfield are NOT done
        let actual_remaining = state
            .piece_manager
            .bitfield
            .iter()
            .filter(|&&status| status != crate::torrent_manager::piece_manager::PieceStatus::Done)
            .count();

        assert_eq!(
            state.piece_manager.pieces_remaining, actual_remaining,
            "Drift detected! PieceManager thinks {} pieces left, but Bitfield shows {}",
            state.piece_manager.pieces_remaining, actual_remaining
        );
    }

    assert!(
        state.total_dl_prev_avg_ema.is_finite(),
        "DL Speed EMA is Infinite/NaN"
    );
    assert!(
        state.total_ul_prev_avg_ema.is_finite(),
        "UL Speed EMA is Infinite/NaN"
    );

    for (id, peer) in &state.peers {
        assert!(
            peer.prev_avg_dl_ema.is_finite(),
            "Peer {} DL EMA is broken",
            id
        );
    }

    if let Some(t) = state.optimistic_unchoke_timer {
        let now = state.now;
        // Allow buffer, but 1 hour in future implies logic error
        if t > now + std::time::Duration::from_secs(3600) {
            panic!("Optimistic timer is set way too far in the future!");
        }
    }

    // CATEGORY 5: LOGICAL INVARIANTS (Protocol & State Logic)

    // We must never ask a peer for a piece they do not possess.
    for (id, peer) in &state.peers {
        for &piece_idx in &peer.pending_requests {
            let has_piece = peer
                .bitfield
                .get(piece_idx as usize)
                .copied()
                .unwrap_or(false);
            assert!(
                has_piece,
                "PROTOCOL VIOLATION: We requested Piece {} from Peer {}, but they do not have it!",
                piece_idx, id
            );
        }
    }

    // If we have pending requests sending to a peer, we MUST claim to be interested in them.
    for (id, peer) in &state.peers {
        if !peer.pending_requests.is_empty() {
            assert!(
                peer.am_interested,
                "STATE ERROR: Peer {} has pending requests but we told them we are NOT interested!",
                id
            );
        }
    }

    // If a peer is choking us, we should not have any active pending requests waiting on them.
    for (id, peer) in &state.peers {
        if peer.peer_choking == crate::torrent_manager::state::ChokeStatus::Choke {
            assert!(
                peer.pending_requests.is_empty(),
                "LOGIC ERROR: Peer {} is Choking us, but we still have pending requests assigned to them!",
                id
            );
        }
    }

    // We should only be interested in a peer if they have a piece we actually need.
    if state.torrent_status != TorrentStatus::Done {
        for (id, peer) in &state.peers {
            if peer.am_interested {
                let interesting = state
                    .piece_manager
                    .need_queue
                    .iter()
                    .chain(state.piece_manager.pending_queue.keys())
                    .any(|&idx| peer.bitfield.get(idx as usize) == Some(&true));

                assert!(
                    interesting,
                    "INEFFICIENCY: We are 'Interested' in Peer {}, but they have NO pieces we currently Need or are Pending.",
                    id
                );
            }
        }
    }

    // If our status is Done, we must strictly have am_interested = false for everyone.
    if state.torrent_status == TorrentStatus::Done {
        for (id, peer) in &state.peers {
            assert!(
                !peer.am_interested,
                "STATE ERROR: Torrent is DONE, but we are still marked 'Interested' in Peer {}!",
                id
            );
        }
    }

    // In Standard mode, a specific piece should strictly be requested from only ONE peer.
    if state.torrent_status == TorrentStatus::Standard {
        let mut requested_pieces = std::collections::HashMap::new();
        for (id, peer) in &state.peers {
            for &piece in &peer.pending_requests {
                if let Some(other_peer) = requested_pieces.insert(piece, id.clone()) {
                    panic!(
                        "INEFFICIENCY: Piece {} is being requested from BOTH {} and {} in Standard mode!",
                        piece, other_peer, id
                    );
                }
            }
        }
    }

    // If we are in Endgame mode, the need_queue MUST be empty.
    if state.torrent_status == TorrentStatus::Endgame {
        assert!(
            state.piece_manager.need_queue.is_empty(),
            "STATE MISMATCH: Status is ENDGAME, but 'need_queue' still contains items!"
        );
        assert!(
            !state.piece_manager.pending_queue.is_empty(),
            "STATE MISMATCH: Status is ENDGAME, but 'pending_queue' is empty! (Should be Done)"
        );
    }

    // We must never unchoke more peers than our allowed maximum (plus allowance for optimistic unchoke).
    let unchoked_count = state
        .peers
        .values()
        .filter(|p| p.am_choking == crate::torrent_manager::state::ChokeStatus::Unchoke)
        .count();

    const MAX_SLOTS: usize = crate::torrent_manager::state::UPLOAD_SLOTS_DEFAULT + 1;

    assert!(
        unchoked_count <= MAX_SLOTS,
        "RESOURCE LEAK: We unchoked {} peers, exceeding the hard limit of {}!",
        unchoked_count,
        MAX_SLOTS
    );
}

// Property-Based Tests (Fuzzing Logic)

#[cfg(test)]
mod prop_tests {

    use super::*;
    use proptest::prelude::*;
    use serde_bencode::value::Value;
    use std::sync::atomic::{AtomicU64, Ordering};
    use tokio::sync::mpsc;

    // --- Constants for Consistent Fuzzing ---
    const PIECE_LEN: u32 = 16384;
    const NUM_PIECES: usize = 20;
    const MAX_BLOCK: u32 = 131_072;

    use rand::rngs::StdRng;
    use rand::{Rng, SeedableRng};

    #[derive(Clone, Debug)]
    enum TorrentVariant {
        V1Single,
        V1Multi,
        Hybrid,
        V2,
    }

    #[derive(Clone, Debug)]
    struct TorrentFuzzCase {
        variant: TorrentVariant,
        piece_length: u32,
        file_lengths: Vec<u64>,
        duplicate_factor: u8,
    }

    fn torrent_shape_strategy() -> impl Strategy<Value = TorrentFuzzCase> {
        (
            0u8..4,
            16384u32..=65536u32,
            proptest::collection::vec(16_384u64..=400_000u64, 1..=4),
            0u8..=2,
        )
            .prop_map(
                |(variant_id, piece_length, mut file_lengths, duplicate_factor)| {
                    let variant = match variant_id {
                        0 => TorrentVariant::V1Single,
                        1 => TorrentVariant::V1Multi,
                        2 => TorrentVariant::Hybrid,
                        _ => TorrentVariant::V2,
                    };

                    if matches!(variant, TorrentVariant::V1Single) {
                        file_lengths.truncate(1);
                    }

                    TorrentFuzzCase {
                        variant,
                        piece_length,
                        file_lengths,
                        duplicate_factor,
                    }
                },
            )
    }

    fn build_fuzz_torrent(case: &TorrentFuzzCase) -> Torrent {
        use crate::torrent_file::{Info, InfoFile, Torrent};

        let piece_len = case.piece_length as u64;
        let total_len: u64 = case.file_lengths.iter().sum();
        let total_piece_count = (total_len.div_ceil(piece_len)) as usize;

        let mut info = Info {
            name: "fuzz_torrent".to_string(),
            piece_length: case.piece_length as i64,
            pieces: vec![0xAB; total_piece_count.saturating_mul(20)],
            length: total_len as i64,
            files: Vec::new(),
            private: None,
            md5sum: None,
            meta_version: None,
            file_tree: None,
        };

        if matches!(
            case.variant,
            TorrentVariant::V1Multi | TorrentVariant::Hybrid
        ) {
            info.length = 0;
            info.files = case
                .file_lengths
                .iter()
                .enumerate()
                .map(|(idx, len)| InfoFile {
                    length: *len as i64,
                    md5sum: None,
                    path: vec![format!("file_{idx}.bin")],
                    attr: None,
                })
                .collect();
        }

        let mut piece_layers = None;

        if matches!(case.variant, TorrentVariant::V2 | TorrentVariant::Hybrid) {
            info.meta_version = Some(2);

            let mut root_node = HashMap::new();
            let mut layers = HashMap::new();

            for (idx, len) in case.file_lengths.iter().enumerate() {
                let root_hash = vec![idx as u8 + 1; 32];
                let file_piece_count = len.div_ceil(piece_len) as usize;
                let mut layer_bytes = Vec::with_capacity(file_piece_count.saturating_mul(32));
                for layer_idx in 0..file_piece_count {
                    layer_bytes.extend_from_slice(&[(layer_idx as u8).wrapping_add(11); 32]);
                }

                layers.insert(root_hash.clone(), Value::Bytes(layer_bytes));

                let mut file_meta = HashMap::new();
                file_meta.insert("length".as_bytes().to_vec(), Value::Int(*len as i64));
                file_meta.insert("pieces root".as_bytes().to_vec(), Value::Bytes(root_hash));

                let mut file_leaf = HashMap::new();
                file_leaf.insert("".as_bytes().to_vec(), Value::Dict(file_meta));
                root_node.insert(
                    format!("v2_file_{idx}").as_bytes().to_vec(),
                    Value::Dict(file_leaf),
                );
            }

            info.file_tree = Some(Value::Dict(root_node));
            piece_layers = Some(Value::Dict(layers));
        }

        if matches!(case.variant, TorrentVariant::V2) {
            info.pieces.clear();
            info.files.clear();
            info.length = 0;
        }

        Torrent {
            announce: None,
            announce_list: None,
            url_list: None,
            info,
            info_dict_bencode: Vec::new(),
            created_by: None,
            creation_date: None,
            encoding: None,
            comment: None,
            piece_layers,
        }
    }

    fn bitfield_has_piece(bitfield: &[u8], piece_index: usize) -> bool {
        let byte_idx = piece_index / 8;
        let bit_idx = 7 - (piece_index % 8);
        bitfield
            .get(byte_idx)
            .map(|b| (b & (1 << bit_idx)) != 0)
            .unwrap_or(false)
    }

    fn encode_bool_bitfield(bits: &[bool]) -> Vec<u8> {
        let mut out = vec![0u8; bits.len().div_ceil(8)];
        for (idx, has_piece) in bits.iter().enumerate() {
            if *has_piece {
                let byte_idx = idx / 8;
                let bit_idx = 7 - (idx % 8);
                out[byte_idx] |= 1 << bit_idx;
            }
        }
        out
    }

    #[derive(Clone, Copy)]
    struct FuzzHarnessConfig {
        peer_count_range: (usize, usize),
        safety_net_peer: bool,
        churn_choke_prob: f64,
        churn_unchoke_prob: f64,
        invalid_verify_prob: f64,
        max_loop_guard: usize,
        delivery_batch_max: usize,
        manager_delivery_batch_max: usize,
        simulated_tick_ms: u64,
        cleanup_interval_ms: u64,
    }

    fn default_harness_config() -> FuzzHarnessConfig {
        FuzzHarnessConfig {
            peer_count_range: (5, 12),
            safety_net_peer: false,
            churn_choke_prob: 0.03,
            churn_unchoke_prob: 0.08,
            invalid_verify_prob: 0.0,
            max_loop_guard: 80_000,
            delivery_batch_max: 6,
            manager_delivery_batch_max: 4,
            simulated_tick_ms: 100,
            cleanup_interval_ms: 3_000,
        }
    }

    enum SimulatedManagerCommand {
        Disconnect(String),
    }

    #[allow(clippy::too_many_arguments)]
    fn enqueue_from_effect(
        effect: Effect,
        state: &TorrentState,
        peer_bitfields_bool: &HashMap<String, Vec<bool>>,
        peer_bitfields_bytes: &HashMap<String, Vec<u8>>,
        pending_actions: &mut Vec<Action>,
        pending_manager_commands: &mut Vec<SimulatedManagerCommand>,
        rng: &mut StdRng,
        duplicate_probability: f64,
        invalid_verify_probability: f64,
    ) {
        match effect {
            Effect::SendToPeer { peer_id, cmd } => {
                if let TorrentCommand::BulkRequest(requests) = *cmd {
                    for (piece_index, block_offset, length) in requests {
                        if let Some(bits) = peer_bitfields_bool.get(&peer_id) {
                            assert!(
                                bits.get(piece_index as usize).copied().unwrap_or(false),
                                "requested piece {piece_index} from peer {peer_id} that does not advertise it"
                            );
                        } else {
                            let bits = peer_bitfields_bytes
                                .get(&peer_id)
                                .expect("peer bitfield should exist");
                            assert!(
                                bitfield_has_piece(bits, piece_index as usize),
                                "requested piece {piece_index} from peer {peer_id} that does not advertise it"
                            );
                        }

                        pending_actions.push(Action::IncomingBlock {
                            peer_id: peer_id.clone(),
                            piece_index,
                            block_offset,
                            data: vec![piece_index as u8; length as usize],
                        });

                        if rng.random_bool(duplicate_probability) {
                            pending_actions.push(Action::IncomingBlock {
                                peer_id: peer_id.clone(),
                                piece_index,
                                block_offset,
                                data: vec![piece_index as u8; length as usize],
                            });
                        }
                    }
                }
            }
            Effect::VerifyPiece {
                peer_id,
                piece_index,
                data,
            }
            | Effect::VerifyPieceV2 {
                peer_id,
                piece_index,
                data,
                ..
            } => {
                let valid = !rng.random_bool(invalid_verify_probability);
                pending_actions.push(Action::PieceVerified {
                    peer_id,
                    piece_index,
                    valid,
                    data,
                });
            }
            Effect::WriteToDisk {
                peer_id,
                piece_index,
                ..
            } => pending_actions.push(Action::PieceWrittenToDisk {
                peer_id,
                piece_index,
            }),
            Effect::DisconnectPeer { peer_id } if state.peers.contains_key(&peer_id) => {
                pending_manager_commands.push(SimulatedManagerCommand::Disconnect(peer_id));
            }
            Effect::DisconnectPeerSession { peer_id, .. } => {
                pending_manager_commands.push(SimulatedManagerCommand::Disconnect(peer_id));
            }
            _ => {}
        }
    }

    fn run_piece_selection_completion_harness(
        case: &TorrentFuzzCase,
        random_seed: u64,
        cfg: FuzzHarnessConfig,
    ) -> Result<(), TestCaseError> {
        let torrent = build_fuzz_torrent(case);
        let mut state = TorrentState {
            torrent_data_path: Some(std::path::PathBuf::from("/tmp")),
            ..Default::default()
        };

        let _ = state.update(Action::MetadataReceived {
            torrent: Box::new(torrent),
            metadata_length: 0,
        });
        state.torrent_status = TorrentStatus::Standard;

        let num_pieces = state.piece_manager.bitfield.len();
        prop_assume!(num_pieces > 0);
        prop_assume!((0..num_pieces).all(|piece_idx| {
            !state
                .piece_manager
                .block_manager
                .piece_block_addresses(piece_idx as u32)
                .is_empty()
        }));

        state.piece_manager.need_queue.clear();
        for piece_idx in 0..num_pieces as u32 {
            state.piece_manager.need_queue.push(piece_idx);
        }

        let mut rng = StdRng::seed_from_u64(random_seed);
        let peer_count = rng.random_range(cfg.peer_count_range.0..=cfg.peer_count_range.1);

        let mut peer_ids = Vec::with_capacity(peer_count);
        for i in 0..peer_count {
            let peer_id = format!("fuzz_peer_{i}");
            let (tx, _rx) = mpsc::channel(16);
            let _ = state.update(Action::RegisterPeer {
                peer_id: peer_id.clone(),
                tx,
            });
            let _ = state.update(Action::PeerSuccessfullyConnected {
                peer_id: peer_id.clone(),
            });
            let _ = state.update(Action::UpdatePeerId {
                peer_addr: peer_id.clone(),
                new_id: peer_id.as_bytes().to_vec(),
            });
            peer_ids.push(peer_id);
        }

        let mut peer_bitfields_bool: HashMap<String, Vec<bool>> = HashMap::new();
        for peer_id in &peer_ids {
            peer_bitfields_bool.insert(peer_id.clone(), vec![false; num_pieces]);
        }

        if cfg.safety_net_peer {
            for (peer_idx, peer_id) in peer_ids.iter().enumerate() {
                if let Some(bits) = peer_bitfields_bool.get_mut(peer_id) {
                    for has_piece in bits.iter_mut().take(num_pieces) {
                        *has_piece = peer_idx == 0 || rng.random_bool(0.5);
                    }
                }
            }
        } else {
            for piece_idx in 0..num_pieces {
                let primary = rng.random_range(0..peer_count);
                peer_bitfields_bool
                    .get_mut(&peer_ids[primary])
                    .expect("primary peer must exist")[piece_idx] = true;

                for peer_id in peer_ids.iter().take(peer_count) {
                    if rng.random_bool(0.2) {
                        peer_bitfields_bool
                            .get_mut(peer_id)
                            .expect("peer must exist")[piece_idx] = true;
                    }
                }
            }

            for piece_idx in 0..num_pieces {
                assert!(peer_ids.iter().any(|pid| {
                    peer_bitfields_bool
                        .get(pid)
                        .and_then(|b| b.get(piece_idx))
                        .copied()
                        .unwrap_or(false)
                }));
            }
        }

        let mut peer_bitfields_bytes: HashMap<String, Vec<u8>> = HashMap::new();
        for peer_id in &peer_ids {
            let bitfield_bool = peer_bitfields_bool
                .get(peer_id)
                .expect("peer bitfield exists");
            let bitfield = encode_bool_bitfield(bitfield_bool);
            peer_bitfields_bytes.insert(peer_id.clone(), bitfield.clone());

            let _ = state.update(Action::PeerBitfieldReceived {
                peer_id: peer_id.clone(),
                bitfield,
            });
        }

        let mut pending_actions: Vec<Action> = Vec::new();
        let mut pending_manager_commands: Vec<SimulatedManagerCommand> = Vec::new();
        for peer_id in &peer_ids {
            let initial = state.update(Action::PeerUnchoked {
                peer_id: peer_id.clone(),
            });
            for effect in initial {
                enqueue_from_effect(
                    effect,
                    &state,
                    &peer_bitfields_bool,
                    &peer_bitfields_bytes,
                    &mut pending_actions,
                    &mut pending_manager_commands,
                    &mut rng,
                    case.duplicate_factor as f64 / 4.0,
                    cfg.invalid_verify_prob,
                );
            }
        }

        state
            .piece_manager
            .update_rarity(state.peers.values().map(|p| &p.bitfield));

        let mut loop_guard = 0usize;
        let mut elapsed_ms = 0u64;
        let cleanup_interval_ms = cfg.cleanup_interval_ms.max(1);
        let mut next_cleanup_ms = cleanup_interval_ms;
        while state.piece_manager.pieces_remaining > 0 {
            loop_guard += 1;
            prop_assert!(
                loop_guard < cfg.max_loop_guard,
                "simulation stalled with {} pending actions, {} pending manager commands, pieces_remaining={}, seed={}",
                pending_actions.len(),
                pending_manager_commands.len(),
                state.piece_manager.pieces_remaining,
                random_seed,
            );

            let mut progressed = false;

            if cfg.churn_choke_prob > 0.0 || cfg.churn_unchoke_prob > 0.0 {
                for peer_id in &peer_ids {
                    if rng.random_bool(cfg.churn_choke_prob) {
                        let _ = state.update(Action::PeerChoked {
                            peer_id: peer_id.clone(),
                        });
                    }
                    if rng.random_bool(cfg.churn_unchoke_prob) {
                        let effects = state.update(Action::PeerUnchoked {
                            peer_id: peer_id.clone(),
                        });
                        if !effects.is_empty() {
                            progressed = true;
                        }
                        for effect in effects {
                            enqueue_from_effect(
                                effect,
                                &state,
                                &peer_bitfields_bool,
                                &peer_bitfields_bytes,
                                &mut pending_actions,
                                &mut pending_manager_commands,
                                &mut rng,
                                case.duplicate_factor as f64 / 4.0,
                                cfg.invalid_verify_prob,
                            );
                        }
                    }
                }
            }

            for peer_id in &peer_ids {
                let effects = state.update(Action::AssignWork {
                    peer_id: peer_id.clone(),
                });
                if !effects.is_empty() {
                    progressed = true;
                }
                for effect in effects {
                    enqueue_from_effect(
                        effect,
                        &state,
                        &peer_bitfields_bool,
                        &peer_bitfields_bytes,
                        &mut pending_actions,
                        &mut pending_manager_commands,
                        &mut rng,
                        case.duplicate_factor as f64 / 4.0,
                        cfg.invalid_verify_prob,
                    );
                }
            }

            if !pending_actions.is_empty() {
                progressed = true;
                let budget = usize::min(
                    pending_actions.len(),
                    rng.random_range(1..=cfg.delivery_batch_max.max(1)),
                );
                for _ in 0..budget {
                    let idx = rng.random_range(0..pending_actions.len());
                    let action = pending_actions.swap_remove(idx);
                    let follow_up = state.update(action);
                    if !follow_up.is_empty() {
                        progressed = true;
                    }
                    for effect in follow_up {
                        enqueue_from_effect(
                            effect,
                            &state,
                            &peer_bitfields_bool,
                            &peer_bitfields_bytes,
                            &mut pending_actions,
                            &mut pending_manager_commands,
                            &mut rng,
                            case.duplicate_factor as f64 / 4.0,
                            cfg.invalid_verify_prob,
                        );
                    }
                    if pending_actions.is_empty() {
                        break;
                    }
                }
            }

            if !pending_manager_commands.is_empty() {
                progressed = true;
                let budget = usize::min(
                    pending_manager_commands.len(),
                    rng.random_range(1..=cfg.manager_delivery_batch_max.max(1)),
                );
                for _ in 0..budget {
                    let idx = rng.random_range(0..pending_manager_commands.len());
                    let cmd = pending_manager_commands.swap_remove(idx);
                    let follow_up = match cmd {
                        SimulatedManagerCommand::Disconnect(peer_id) => {
                            state.update(Action::PeerDisconnected {
                                peer_id,
                                force: false,
                            })
                        }
                    };
                    if !follow_up.is_empty() {
                        progressed = true;
                    }
                    for effect in follow_up {
                        enqueue_from_effect(
                            effect,
                            &state,
                            &peer_bitfields_bool,
                            &peer_bitfields_bytes,
                            &mut pending_actions,
                            &mut pending_manager_commands,
                            &mut rng,
                            case.duplicate_factor as f64 / 4.0,
                            cfg.invalid_verify_prob,
                        );
                    }
                    if pending_manager_commands.is_empty() {
                        break;
                    }
                }
            }

            elapsed_ms = elapsed_ms.saturating_add(cfg.simulated_tick_ms);
            while elapsed_ms >= next_cleanup_ms {
                let cleanup_effects = state.update(Action::Cleanup);
                if !cleanup_effects.is_empty() {
                    progressed = true;
                }
                for effect in cleanup_effects {
                    enqueue_from_effect(
                        effect,
                        &state,
                        &peer_bitfields_bool,
                        &peer_bitfields_bytes,
                        &mut pending_actions,
                        &mut pending_manager_commands,
                        &mut rng,
                        case.duplicate_factor as f64 / 4.0,
                        cfg.invalid_verify_prob,
                    );
                }
                next_cleanup_ms = next_cleanup_ms.saturating_add(cleanup_interval_ms);
            }

            if !progressed && pending_actions.is_empty() && pending_manager_commands.is_empty() {
                for peer_id in &peer_ids {
                    let unchoke_effects = state.update(Action::PeerUnchoked {
                        peer_id: peer_id.clone(),
                    });
                    if !unchoke_effects.is_empty() {
                        progressed = true;
                    }
                    for effect in unchoke_effects {
                        enqueue_from_effect(
                            effect,
                            &state,
                            &peer_bitfields_bool,
                            &peer_bitfields_bytes,
                            &mut pending_actions,
                            &mut pending_manager_commands,
                            &mut rng,
                            case.duplicate_factor as f64 / 4.0,
                            cfg.invalid_verify_prob,
                        );
                    }
                    let effects = state.update(Action::AssignWork {
                        peer_id: peer_id.clone(),
                    });
                    for effect in effects {
                        enqueue_from_effect(
                            effect,
                            &state,
                            &peer_bitfields_bool,
                            &peer_bitfields_bytes,
                            &mut pending_actions,
                            &mut pending_manager_commands,
                            &mut rng,
                            case.duplicate_factor as f64 / 4.0,
                            cfg.invalid_verify_prob,
                        );
                    }
                }
            }

            if !(progressed || !pending_actions.is_empty() || !pending_manager_commands.is_empty())
            {
                let queued_piece_count =
                    state.piece_manager.need_queue.len() + state.piece_manager.pending_queue.len();
                let has_serviceable_piece = state
                    .piece_manager
                    .need_queue
                    .iter()
                    .chain(state.piece_manager.pending_queue.keys())
                    .any(|piece_idx| {
                        state
                            .peers
                            .values()
                            .any(|peer| peer.bitfield.get(*piece_idx as usize) == Some(&true))
                    });
                let pending_without_owner = state
                    .piece_manager
                    .pending_queue
                    .keys()
                    .filter(|piece_idx| {
                        !state
                            .peers
                            .values()
                            .any(|peer| peer.pending_requests.contains(piece_idx))
                    })
                    .count();
                let pending_requestable_blocks: usize = state
                    .piece_manager
                    .pending_queue
                    .keys()
                    .map(|piece_idx| {
                        state
                            .piece_manager
                            .requestable_block_addresses_for_piece(*piece_idx)
                            .len()
                    })
                    .sum();
                let peers_with_pending_requests = state
                    .peers
                    .values()
                    .filter(|peer| !peer.pending_requests.is_empty())
                    .count();

                prop_assert!(
                    false,
                    "no progress and no pending work after recovery, pieces_remaining={}, pending_actions={}, pending_manager_commands={}, pending_disconnects={}, need_queue={}, pending_queue={}, queued_piece_count={}, has_serviceable_piece={}, pending_without_owner={}, pending_requestable_blocks={}, peers_with_pending_requests={}, peers={}, seed={}, loop_guard={}",
                    state.piece_manager.pieces_remaining,
                    pending_actions.len(),
                    pending_manager_commands.len(),
                    state.pending_disconnects.len(),
                    state.piece_manager.need_queue.len(),
                    state.piece_manager.pending_queue.len(),
                    queued_piece_count,
                    has_serviceable_piece,
                    pending_without_owner,
                    pending_requestable_blocks,
                    peers_with_pending_requests,
                    state.peers.len(),
                    random_seed,
                    loop_guard,
                );
            }
        }

        prop_assert_eq!(state.piece_manager.pieces_remaining, 0);
        prop_assert!(state
            .piece_manager
            .bitfield
            .iter()
            .all(|status| *status == PieceStatus::Done));

        Ok(())
    }

    static FUZZ_CASE_COUNTER: AtomicU64 = AtomicU64::new(0);

    proptest! {
        #[test]
        fn fuzz_piece_block_selection_and_completion(
            case in torrent_shape_strategy(),
            random_seed in any::<u64>(),
        ) {
            let case_no = FUZZ_CASE_COUNTER.fetch_add(1, Ordering::Relaxed) + 1;
            if case_no.is_multiple_of(10_000) {
                println!("current run {}", case_no);
            }
            run_piece_selection_completion_harness(
                &case,
                random_seed,
                default_harness_config(),
            )?;
        }
    }

    #[derive(Clone, Debug)]
    enum NetworkFault {
        None,
        Drop,
        Duplicate,
        Delay(u64),
        Corrupt,
    }

    fn inject_reordering_faults(actions: Vec<Action>, seed: u64) -> Vec<Action> {
        // We use a fixed seed from Proptest so failures are reproducible
        let mut rng = StdRng::seed_from_u64(seed);

        let mut pending = Vec::new();
        let mut result = Vec::new();

        for action in actions {
            // 2% Packet Loss
            if rng.random_bool(0.02) {
                continue;
            }

            // 1% Duplication (Clone creates the "Ghost Packet")
            if rng.random_bool(0.01) {
                let delay = rng.random_range(10..400);
                pending.push((delay, action.clone()));
            }

            // Normal Delivery (random delay 10ms - 400ms)
            let delay = rng.random_range(10..400);
            pending.push((delay, action));
        }

        // Sort events by who arrives first. This shuffles the timeline.
        pending.sort_by_key(|(delay, _)| *delay);

        // We must insert 'Tick' actions to account for the time gaps between events.
        let mut current_time = 0;
        for (arrival_time, action) in pending {
            if arrival_time > current_time {
                result.push(Action::Tick {
                    dt_ms: arrival_time - current_time,
                });
                current_time = arrival_time;
            }
            result.push(action);
        }

        result
    }

    // Transforms a clean history of actions into a faulty network stream
    // deterministically based on a vector of random "fault seeds"
    fn inject_network_faults(actions: Vec<Action>, fault_entropy: Vec<u8>) -> Vec<Action> {
        let mut final_actions = Vec::new();
        // Cycle through entropy so we don't run out if actions > entropy length
        let mut entropy_iter = fault_entropy.iter().cycle();

        for action in actions {
            let seed = *entropy_iter.next().unwrap();

            // Map the random byte (0-255) to a Fault Type
            let fault = match seed {
                0..=4 => NetworkFault::Drop,                      // ~2% chance
                5..=9 => NetworkFault::Duplicate,                 // ~2% chance
                10..=20 => NetworkFault::Delay(seed as u64 * 50), // ~4% chance (500ms-1000ms)
                21..=25 => NetworkFault::Corrupt,                 // ~2% chance
                _ => NetworkFault::None,                          // ~90% Clean
            };

            match fault {
                NetworkFault::Drop => {
                    // Packet lost in the ether
                    continue;
                }
                NetworkFault::Duplicate => {
                    final_actions.push(action.clone());
                    final_actions.push(action);
                }
                NetworkFault::Delay(ms) => {
                    // Simulate delay by ticking the clock before delivery
                    final_actions.push(Action::Tick { dt_ms: ms });
                    final_actions.push(action);
                }
                NetworkFault::Corrupt => {
                    // Flip bits if it involves data
                    match action {
                        Action::IncomingBlock {
                            peer_id,
                            piece_index,
                            block_offset,
                            mut data,
                        } => {
                            if !data.is_empty() {
                                // Corrupt the last byte
                                let len = data.len();
                                data[len - 1] = !data[len - 1];
                            }
                            final_actions.push(Action::IncomingBlock {
                                peer_id,
                                piece_index,
                                block_offset,
                                data,
                            });
                        }
                        // For control packets, corruption usually means they fail parsing
                        // and are effectively dropped or cause a disconnect.
                        // We simulate "parsing error" by turning it into a connection failure or drop.
                        _ => {
                            // Simulate packet garbling leading to drop
                            continue;
                        }
                    }
                }
                NetworkFault::None => {
                    final_actions.push(action);
                }
            }
        }
        final_actions
    }

    fn tit_for_tat_strategy() -> impl Strategy<Value = TorrentState> {
        let num_peers = 10usize;
        let speeds_strat = proptest::collection::vec(0..100_000u64, num_peers);

        speeds_strat.prop_map(move |speeds| {
            let mut state = super::tests::create_empty_state();
            state.torrent_status = TorrentStatus::Standard;

            for (i, &speed) in speeds.iter().enumerate() {
                let id = format!("peer_{}", i);
                let (tx, _) = mpsc::channel(1);
                let mut peer = PeerState::new(id.clone(), tx, state.now);

                peer.peer_id = id.as_bytes().to_vec();
                peer.peer_is_interested_in_us = true;
                peer.am_choking = super::ChokeStatus::Choke;

                peer.bytes_downloaded_from_peer = speed;

                state.peers.insert(id, peer);
            }
            state.number_of_successfully_connected_peers = state.peers.len();

            state
        })
    }

    fn rarest_first_strategy() -> impl Strategy<Value = TorrentState> {
        Just(()).prop_map(|_| {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(2);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(2, false);
            state.piece_manager.block_manager.set_geometry(
                16384,
                16384 * 2,
                vec![],
                vec![],
                HashMap::new(),
                false,
            );
            state.torrent_status = TorrentStatus::Standard;

            state.piece_manager.need_queue = vec![0, 1];

            // ... (Same peer creation code as before) ...
            let target_id = "target_peer".to_string();
            let (tx, _) = mpsc::channel(1);
            let mut target = PeerState::new(target_id.clone(), tx, state.now);
            target.peer_id = target_id.as_bytes().to_vec();
            target.peer_choking = super::ChokeStatus::Unchoke;
            target.am_interested = true;
            target.bitfield = vec![true, true];
            state.peers.insert(target_id, target);

            for i in 0..5 {
                let id = format!("bg_peer_{}", i);
                let (tx, _) = mpsc::channel(1);
                let mut p = PeerState::new(id.clone(), tx, state.now);
                p.peer_id = id.as_bytes().to_vec();
                p.bitfield = vec![false, true];
                state.peers.insert(id, p);
            }

            state.number_of_successfully_connected_peers = state.peers.len();

            state
                .piece_manager
                .update_rarity(state.peers.values().map(|p| &p.bitfield));

            state
        })
    }

    // Creates a swarm where EVERYONE is slow.
    // Tests if the client correctly handles mutual choking (snubbing).
    fn tit_for_tat_snubbed_strategy() -> impl Strategy<Value = TorrentState> {
        // 10 peers, all with 0 or 1 byte downloaded (Snubbed)
        let speeds_strat = proptest::collection::vec(0..=1u64, 10);

        speeds_strat.prop_map(move |speeds| {
            let mut state = super::tests::create_empty_state();
            state.torrent_status = TorrentStatus::Standard;

            for (i, &speed) in speeds.iter().enumerate() {
                let id = format!("slow_peer_{}", i);
                let (tx, _) = mpsc::channel(1);
                let mut peer = PeerState::new(id.clone(), tx, state.now);
                peer.peer_id = id.as_bytes().to_vec();
                peer.peer_is_interested_in_us = true;
                peer.am_choking = super::ChokeStatus::Choke;
                // Crucial: Low speed triggers snubbing logic (if implemented)
                peer.bytes_downloaded_from_peer = speed;
                state.peers.insert(id, peer);
            }
            state.number_of_successfully_connected_peers = state.peers.len();
            state
        })
    }

    // --- STRATEGY 4: Rarest First "Tiebreaker" Variant ---
    // Creates a scenario with two equally rare pieces (0 and 1).
    // Tests deterministic tie-breaking logic.
    fn rarest_first_tie_strategy() -> impl Strategy<Value = TorrentState> {
        Just(()).prop_map(|_| {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(2);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(2, false);
            state.piece_manager.block_manager.set_geometry(
                16384,
                16384 * 2,
                vec![],
                vec![],
                HashMap::new(),
                false,
            );
            state.torrent_status = TorrentStatus::Standard;
            state.piece_manager.need_queue = vec![0, 1];

            let target_id = "target_peer".to_string();
            let (tx, _) = mpsc::channel(1);
            let mut target = PeerState::new(target_id.clone(), tx, state.now);
            target.peer_id = target_id.as_bytes().to_vec();
            target.peer_choking = super::ChokeStatus::Unchoke;
            target.am_interested = true;
            target.bitfield = vec![true, true];
            state.peers.insert(target_id, target);

            state.number_of_successfully_connected_peers = state.peers.len();

            state
                .piece_manager
                .update_rarity(state.peers.values().map(|p| &p.bitfield));
            state
        })
    }

    // --- STRATEGY 5: Integrated Algo Strategy ---
    // Mixes speeds and bitfields to test the interaction between Choking and Picking.
    fn combined_algo_strategy() -> impl Strategy<Value = TorrentState> {
        // Peer A: Fast but has Common piece
        // Peer B: Slow but has Rare piece
        // Peer C: Medium speed, has Both
        Just(()).prop_map(move |_| {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(2);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(2, false);
            state.piece_manager.block_manager.set_geometry(
                16384,
                16384 * 2,
                vec![],
                vec![],
                HashMap::new(),
                false,
            );
            state.torrent_status = TorrentStatus::Standard;
            state.piece_manager.need_queue = vec![0, 1];

            // Helper to add peer
            let mut add_peer = |id: &str, speed: u64, pieces: Vec<bool>| {
                let (tx, _) = mpsc::channel(1);
                let mut p = PeerState::new(id.to_string(), tx, state.now);
                p.peer_id = id.as_bytes().to_vec();
                p.peer_is_interested_in_us = true; // We want to upload to them
                p.peer_choking = super::ChokeStatus::Unchoke; // They let us DL
                p.am_interested = true; // We want to DL
                p.bytes_downloaded_from_peer = speed; // For Tit-for-Tat
                p.bitfield = pieces; // For Rarest First
                state.peers.insert(id.to_string(), p);
            };

            // Setup the scenario
            add_peer("fast_common", 100_000, vec![false, true]); // Has Piece 1 (Common)
            add_peer("slow_rare", 100, vec![true, false]); // Has Piece 0 (Rare)
            add_peer("medium_both", 50_000, vec![true, true]); // Has Both

            state.number_of_successfully_connected_peers = state.peers.len();

            // Sync Rarity: Piece 0 (2 copies), Piece 1 (2 copies) -> Equal rarity in this setup
            state
                .piece_manager
                .update_rarity(state.peers.values().map(|p| &p.bitfield));

            state
        })
    }

    // --- STRATEGY 6: The Free-Rider (Parasite) Scenario ---
    // Creates a scenario with:

    // Both want our data. Logic MUST favor the Hero.
    fn free_rider_strategy() -> impl Strategy<Value = TorrentState> {
        Just(()).prop_map(move |_| {
            let mut state = super::tests::create_empty_state();
            state.torrent_status = TorrentStatus::Standard; // Leeching mode

            // Use the fixed constant defined in state.rs (which is 4)
            const UPLOAD_SLOTS: usize = super::UPLOAD_SLOTS_DEFAULT;

            let hero_id = "hero_peer".to_string();
            let (tx1, _) = mpsc::channel(1);
            let mut hero = PeerState::new(hero_id.clone(), tx1, state.now);
            hero.peer_id = hero_id.as_bytes().to_vec();
            hero.peer_is_interested_in_us = true;
            hero.am_choking = super::ChokeStatus::Choke;
            hero.bytes_downloaded_from_peer = 1_000_000; // High contribution
            state.peers.insert(hero_id, hero);

            // These peers, plus the Hero, will consume the 4 upload slots.
            // The loop runs from 1 to UPLOAD_SLOTS_DEFAULT (4).
            for i in 1..=UPLOAD_SLOTS {
                let id = format!("med_peer_{}", i);
                let (tx, _) = mpsc::channel(1);
                let mut p = PeerState::new(id.clone(), tx, state.now);
                p.peer_id = id.as_bytes().to_vec();
                p.peer_is_interested_in_us = true;
                p.am_choking = super::ChokeStatus::Choke;
                p.bytes_downloaded_from_peer = 100; // Better than 0
                state.peers.insert(id, p);
            }

            let leech_id = "parasite_peer".to_string();
            let (tx2, _) = mpsc::channel(1);
            let mut leech = PeerState::new(leech_id.clone(), tx2, state.now);
            leech.peer_id = leech_id.as_bytes().to_vec();
            leech.peer_is_interested_in_us = true;
            leech.am_choking = super::ChokeStatus::Choke;
            leech.bytes_downloaded_from_peer = 0; // No contribution
            state.peers.insert(leech_id, leech);

            // Total peers: Hero (1) + Med Peers (4) + Parasite (1) = 6
            // Total slots: 4 (Deterministic)
            // Since there are 5 peers contributing more than 0, the parasite (0) loses.

            state.number_of_successfully_connected_peers = state.peers.len();
            state
        })
    }

    // --- STRATEGY 8: Huge Swarm Strategy (Scale Test) ---
    // Scenario: 1000 Peers. Piece 0 is on 1 peer. Piece 1 is on 999 peers.
    // Goal: Ensure O(n) rarity calculation doesn't crash or timeout.
    fn huge_swarm_strategy() -> impl Strategy<Value = TorrentState> {
        Just(()).prop_map(|_| {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(2);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(2, false);
            state.piece_manager.block_manager.set_geometry(
                16384,
                16384 * 2,
                vec![],
                vec![],
                HashMap::new(),
                false,
            );
            state.torrent_status = TorrentStatus::Standard;
            state.piece_manager.need_queue = vec![0, 1];

            let rare_id = "rare_peer".to_string();
            let (tx, _) = mpsc::channel(1);
            let mut rare = PeerState::new(rare_id.clone(), tx, state.now);
            rare.peer_id = rare_id.as_bytes().to_vec();
            rare.peer_choking = super::ChokeStatus::Unchoke;
            rare.am_interested = true;
            rare.bitfield = vec![true, false]; // Has 0
            state.peers.insert(rare_id, rare);

            // We optimize this loop to avoid 1000 channel allocations slowing down the test setup too much
            let (tx, _) = mpsc::channel(1);
            for i in 0..999 {
                let id = format!("common_{}", i);
                let mut p = PeerState::new(id.clone(), tx.clone(), state.now);
                p.peer_id = id.as_bytes().to_vec();
                p.bitfield = vec![false, true]; // Has 1
                state.peers.insert(id, p);
            }
            state.number_of_successfully_connected_peers = state.peers.len();

            state
                .piece_manager
                .update_rarity(state.peers.values().map(|p| &p.bitfield));
            state
        })
    }

    // A strategy that forces the State Machine through specific "Phases"
    // instead of just throwing random events at it.
    fn lifecycle_transition_strategy() -> impl Strategy<Value = Vec<Action>> {
        let peer_id = "lifecycle_peer".to_string();

        prop_oneof![
            // Case 1: The Endgame Transition
            // Force queue to empty, then verify redundant requests behavior
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: peer_id.clone()
                },
                Action::PeerUnchoked {
                    peer_id: peer_id.clone()
                },
                Action::PeerHavePiece {
                    peer_id: peer_id.clone(),
                    piece_index: 0
                },
                Action::AssignWork {
                    peer_id: peer_id.clone()
                },
                // (We would need to manually manipulate the state queue in the test runner
                //  for this to work perfectly, or send a specific sequence here).
            ]),
            // Case 2: The "Stuck Peer" Cleanup
            // Connect a peer, Advance time > 5s, Trigger Cleanup
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: peer_id.clone()
                },
                // Note: We intentionally do NOT send SetPeerId here
                Action::Tick { dt_ms: 6000 },
                Action::Cleanup,
                // Expectation: Peer should be removed
            ]),
            // Case 3: Pause/Resume Data Integrity
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: peer_id.clone()
                },
                Action::IncomingBlock {
                    peer_id: peer_id.clone(),
                    piece_index: 0,
                    block_offset: 0,
                    data: vec![1; 100]
                },
                Action::Pause,
                Action::Resume,
                // Re-connect is required after pause
                Action::PeerSuccessfullyConnected {
                    peer_id: peer_id.clone()
                },
                // Try sending the SAME block again.
                // If internal state wasn't cleared, this might panic or corrupt.
                Action::IncomingBlock {
                    peer_id: peer_id.clone(),
                    piece_index: 0,
                    block_offset: 0,
                    data: vec![1; 100]
                },
            ])
        ]
    }

    fn network_action_strategy() -> impl Strategy<Value = Action> {
        let peer_id_strat = proptest::string::string_regex(".+").unwrap().boxed();

        prop_oneof![
            peer_id_strat
                .clone()
                .prop_map(|id| Action::PeerSuccessfullyConnected { peer_id: id }),
            peer_id_strat
                .clone()
                .prop_map(|id| Action::PeerDisconnected {
                    peer_id: id,
                    force: true
                }),
            any::<String>().prop_map(|addr| Action::PeerConnectionFailed { peer_addr: addr }),
            (any::<String>(), proptest::collection::vec(any::<u8>(), 20)).prop_map(|(addr, id)| {
                Action::UpdatePeerId {
                    peer_addr: addr,
                    new_id: id,
                }
            }),
            (any::<String>(), any::<u64>()).prop_map(|(url, interval)| {
                Action::TrackerResponse {
                    url,
                    peers: vec![],
                    interval,
                    min_interval: Some(60),
                }
            }),
            any::<String>().prop_map(|url| Action::TrackerError { url }),
            Just(Action::UpdateListenPort),
        ]
    }

    fn protocol_action_strategy() -> impl Strategy<Value = Action> {
        let peer_id_strat = proptest::string::string_regex(".+").unwrap().boxed();

        prop_oneof![
            peer_id_strat
                .clone()
                .prop_map(|id| Action::PeerChoked { peer_id: id }),
            peer_id_strat
                .clone()
                .prop_map(|id| Action::PeerUnchoked { peer_id: id }),
            peer_id_strat
                .clone()
                .prop_map(|id| Action::PeerInterested { peer_id: id }),
            (
                peer_id_strat.clone(),
                proptest::collection::vec(any::<u8>(), 1..10)
            )
                .prop_map(|(id, bf)| {
                    Action::PeerBitfieldReceived {
                        peer_id: id,
                        bitfield: bf,
                    }
                }),
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                Action::PeerHavePiece {
                    peer_id: id,
                    piece_index: idx,
                }
            }),
            peer_id_strat.prop_map(|id| Action::AssignWork { peer_id: id }),
        ]
    }

    fn boundary_data_strategy() -> impl Strategy<Value = Action> {
        let peer_id_strat = proptest::string::string_regex(".+").unwrap().boxed();

        prop_oneof![
            // FIX: Access NUM_PIECES and PIECE_LEN directly
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                let data = vec![1u8; 1024];
                Action::IncomingBlock {
                    peer_id: id,
                    piece_index: idx,
                    block_offset: PIECE_LEN - 1024,
                    data,
                }
            }),
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                let data = vec![0u8; 10];
                Action::IncomingBlock {
                    peer_id: id,
                    piece_index: idx,
                    block_offset: PIECE_LEN - 5,
                    data,
                }
            }),
            // FIX: Access MAX_BLOCK directly
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                Action::RequestUpload {
                    peer_id: id,
                    piece_index: idx,
                    block_offset: 0,
                    length: MAX_BLOCK + 1,
                }
            }),
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                Action::RequestUpload {
                    peer_id: id,
                    piece_index: idx,
                    block_offset: 0,
                    length: 0,
                }
            }),
            (
                peer_id_strat.clone(),
                0..NUM_PIECES as u32,
                any::<u32>(),
                proptest::collection::vec(any::<u8>(), 1..1024)
            )
                .prop_map(|(id, idx, off, data)| Action::IncomingBlock {
                    peer_id: id,
                    piece_index: idx,
                    block_offset: off,
                    data
                }),
        ]
    }

    fn system_response_strategy() -> impl Strategy<Value = Action> {
        let peer_id_strat = proptest::string::string_regex(".+").unwrap().boxed();

        prop_oneof![
            // FIX: Access NUM_PIECES directly
            (peer_id_strat.clone(), 0..NUM_PIECES as u32, any::<bool>()).prop_map(
                |(id, idx, valid)| {
                    Action::PieceVerified {
                        peer_id: id,
                        piece_index: idx,
                        valid,
                        data: vec![],
                    }
                }
            ),
            (peer_id_strat.clone(), 0..NUM_PIECES as u32).prop_map(|(id, idx)| {
                Action::PieceWrittenToDisk {
                    peer_id: id,
                    piece_index: idx,
                }
            }),
            any::<u32>().prop_map(|idx| Action::PieceWriteFailed { piece_index: idx }),
            proptest::collection::vec(0..NUM_PIECES as u32, 0..5).prop_map(|pieces| {
                Action::ValidationComplete {
                    completed_pieces: pieces,
                }
            }),
        ]
    }

    // E. Global Lifecycle
    fn lifecycle_strategy() -> impl Strategy<Value = Action> {
        prop_oneof![
            Just(Action::Tick { dt_ms: 100 }),
            Just(Action::Tick { dt_ms: 50000 }),
            Just(Action::CheckCompletion),
            Just(Action::Cleanup),
            Just(Action::Pause),
            Just(Action::Resume),
            (0..50u64).prop_map(|seed| Action::RecalculateChokes { random_seed: seed }),
        ]
    }

    // F. Combined Chaos
    fn chaos_strategy() -> impl Strategy<Value = Action> {
        prop_oneof![
            network_action_strategy(),
            protocol_action_strategy(),
            boundary_data_strategy(), // Using the new boundary strategy here
            system_response_strategy(),
            lifecycle_strategy(),
        ]
    }

    fn protocol_violation_strategy() -> impl Strategy<Value = Vec<Action>> {
        let id = "bad_actor".to_string();

        prop_oneof![
            // Expectation: Data should be dropped or peer disconnected, no panic.
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: id.clone()
                },
                Action::PeerChoked {
                    peer_id: id.clone()
                }, // They choked us
                Action::IncomingBlock {
                    peer_id: id.clone(),
                    piece_index: 0,
                    block_offset: 0,
                    data: vec![0; 100]
                }
            ]),
            // Expectation: Request ignored, strict clients might disconnect peer.
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: id.clone()
                },
                Action::PeerUnchoked {
                    peer_id: id.clone()
                },
                Action::RequestUpload {
                    peer_id: id.clone(),
                    piece_index: 99999, // Way out of bounds
                    block_offset: 0,
                    length: 16384
                }
            ]),
            // Expectation: State handles map collisions gracefully.
            Just(vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: id.clone()
                },
                Action::PeerSuccessfullyConnected {
                    peer_id: id.clone()
                }, // Re-connect
                Action::PeerDisconnected {
                    peer_id: id.clone(),
                    force: true,
                },
                // Should be ignored or handled gracefully, not panic
                Action::IncomingBlock {
                    peer_id: id.clone(),
                    piece_index: 0,
                    block_offset: 0,
                    data: vec![1]
                }
            ]),
            // Expectation: Client accepts the byte into a buffer OR drops it. MUST NOT PANIC.
            // Malicious peers do this to exhaust memory 1 byte at a time.
            (0..20u32).prop_map(|idx| {
                let frag_id = "fragmenter".to_string();
                vec![
                    Action::PeerSuccessfullyConnected {
                        peer_id: frag_id.clone(),
                    },
                    Action::PeerUnchoked {
                        peer_id: frag_id.clone(),
                    },
                    Action::IncomingBlock {
                        peer_id: frag_id.clone(),
                        piece_index: idx,
                        block_offset: 0,
                        data: vec![0u8; 1], // <--- The Attack: Exactly 1 byte
                    },
                ]
            })
        ]
    }

    // Standard Stories (kept for logical flow testing)
    fn successful_download_story() -> impl Strategy<Value = Vec<Action>> {
        // Shortened version for brevity, assuming previous implementation logic
        let peer_gen = (1..255u8, 1000..9999u16);
        let piece_gen = 0..NUM_PIECES as u32;

        (peer_gen, piece_gen).prop_flat_map(|((ip, port), piece_index)| {
            let peer_id = format!("127.0.0.{}:{}", ip, port);
            let data = vec![1, 2, 3, 4];
            let actions = vec![
                Action::PeerSuccessfullyConnected {
                    peer_id: peer_id.clone(),
                },
                Action::PeerBitfieldReceived {
                    peer_id: peer_id.clone(),
                    bitfield: vec![],
                },
                Action::PeerHavePiece {
                    peer_id: peer_id.clone(),
                    piece_index,
                },
                Action::PeerUnchoked {
                    peer_id: peer_id.clone(),
                },
                Action::IncomingBlock {
                    peer_id: peer_id.clone(),
                    piece_index,
                    block_offset: 0,
                    data: data.clone(),
                },
                Action::PieceVerified {
                    peer_id: peer_id.clone(),
                    piece_index,
                    valid: true,
                    data,
                },
                Action::PieceWrittenToDisk {
                    peer_id: peer_id.clone(),
                    piece_index,
                },
            ];
            Just(actions)
        })
    }

    // Master Strategy
    fn mixed_behavior_strategy() -> impl Strategy<Value = Vec<Action>> {
        prop_oneof![
            4 => chaos_strategy().prop_map(|a| vec![a]),
            2 => successful_download_story(),
            1 => protocol_violation_strategy(),
            1 => lifecycle_transition_strategy(),
        ]
    }

    fn populated_state_strategy() -> impl Strategy<Value = TorrentState> {
        let peers_strat = proptest::collection::hash_map(
            any::<String>(),
            // (Download Speed, Upload Speed, Has Piece 0?)
            (any::<u64>(), any::<u64>(), any::<bool>()),
            1..20,
        );

        peers_strat.prop_map(|peer_map| {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(NUM_PIECES);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(NUM_PIECES, false);
            state.torrent_status = TorrentStatus::Standard;

            // Pre-fill peers
            for (id, (dl, ul, has_piece_0)) in peer_map {
                let (tx, _) = mpsc::channel(1);
                let mut peer = PeerState::new(id.clone(), tx, state.now);

                peer.peer_id = id.as_bytes().to_vec();

                peer.bitfield = vec![false; NUM_PIECES];
                if has_piece_0 {
                    peer.bitfield[0] = true;
                }

                // In this strategy we need all pieces, so if they have any, we are interested.
                peer.am_interested = peer.bitfield.iter().any(|&b| b);

                peer.peer_is_interested_in_us = true;
                peer.peer_choking = crate::torrent_manager::state::ChokeStatus::Unchoke;

                // Pre-load stats to influence Choke/Unchoke logic
                peer.bytes_downloaded_in_tick = dl % 100_000;
                peer.bytes_uploaded_in_tick = ul % 100_000;
                peer.download_speed_bps = dl % 100_000;

                state.peers.insert(id, peer);
            }

            // --- FIX START: Sync the metric count with the inserted peers ---
            state.number_of_successfully_connected_peers = state.peers.len();
            // --- FIX END ---

            // IMPORTANT: Ensure Need Queue is populated so AssignWork actually does something
            state.piece_manager.need_queue.clear();
            for i in 0..NUM_PIECES as u32 {
                state.piece_manager.need_queue.push(i);
            }

            state
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::default())]

        // Test 1: Logical Stories starting from scratch
        #[test]
        fn test_stateful_stories(
            story_batches in proptest::collection::vec(mixed_behavior_strategy(), 1..15)
        ) {
            let mut state = super::tests::create_empty_state();
            let torrent = super::tests::create_dummy_torrent(NUM_PIECES);
            state.torrent = Some(torrent);
            state.piece_manager.set_initial_fields(NUM_PIECES, false);
            state.torrent_status = TorrentStatus::Standard;
            state.piece_manager.need_queue = (0..NUM_PIECES as u32).collect();

            for story in story_batches {
                for action in story {
                     // Adapter for handshake simulation
                    if let Action::PeerSuccessfullyConnected { peer_id } = &action {
                        if !state.peers.contains_key(peer_id) {
                            let (tx, _) = mpsc::channel(1);
                            let mut peer = PeerState::new(peer_id.clone(), tx, state.now);
                            peer.peer_id = peer_id.as_bytes().to_vec();
                            state.peers.insert(peer_id.clone(), peer);
                        }
                    }
                    let _ = state.update(action);
                    check_invariants(&state);
                }
            }
        }

        // Test 2: Deep State Fuzzing (New Strategies)
        // Starts with a populated state and applies Chaos + Boundary Data
        #[test]
        fn test_deep_state_chaos(
            mut initial_state in populated_state_strategy(),
            actions in proptest::collection::vec(chaos_strategy(), 1..20)
        ) {
            // Sanity check initial state
            check_invariants(&initial_state);

            for action in actions {
                // Use catch_unwind to fail the test gracefully if a panic occurs,
                // allowing Proptest to print the shrinking failure case.
                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    // Adapter for handshake simulation (even in chaos mode)
                    if let Action::PeerSuccessfullyConnected { peer_id } = &action {
                        // We allow overwrites in Chaos mode to test resilience
                        if !initial_state.peers.contains_key(peer_id) {
                            let (tx, _) = mpsc::channel(1);
                            let mut peer = PeerState::new(peer_id.clone(), tx, initial_state.now);
                            peer.peer_id = peer_id.as_bytes().to_vec();
                            initial_state.peers.insert(peer_id.clone(), peer);
                        }
                    }

                    let _ = initial_state.update(action.clone());
                }));

                if result.is_err() {
                     // If we panicked, the test fails here.
                     // Proptest will output the `initial_state` and the `actions` vector.
                     panic!("Deep State Fuzzing Triggered Panic!");
                }

                check_invariants(&initial_state);
            }
        }

        #[test]
        fn test_tit_for_tat_fairness(mut state  in tit_for_tat_strategy()) {
            let mut peers: Vec<_> = state.peers.values().collect();

            // Sort Descending by speed
            peers.sort_by_key(|peer| std::cmp::Reverse(peer.bytes_downloaded_from_peer));

            let top_peers: Vec<String> = peers.iter()
                .take(UPLOAD_SLOTS_DEFAULT)
                .map(|p| p.ip_port.clone())
                .collect();

            // Run Algorithm
            let _ = state.update(Action::RecalculateChokes {
                random_seed: 12345
            });

            // Assert Fairness
            for winner_id in top_peers {
                let peer = state.peers.get(&winner_id).unwrap();
                prop_assert_eq!(peer.am_choking.clone(), super::ChokeStatus::Unchoke,
                    "Fast peer {} was unfairly choked!", winner_id);
            }
        }

        #[test]
    fn test_rarest_first_selection(mut state in rarest_first_strategy()) {

            let effects = state.update(Action::AssignWork { peer_id: "target_peer".into() });

            let requested_index = effects.iter().find_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                        return reqs.first().map(|(idx, _, _)| *idx);
                    }
                }
                None
            });

            if let Some(idx) = requested_index {
                prop_assert_eq!(idx, 0,
                    "Algorithm picked Common Piece {} instead of Rare Piece 0", idx);
            } else {
                prop_assert!(false, "Algorithm failed to request any piece! State: {:?}", state);
            }
        }

        // --- TEST 3: Tit-for-Tat Snubbed Invariant ---
        #[test]
        fn test_tit_for_tat_snubbed(mut state in tit_for_tat_snubbed_strategy()) {

            let _ = state.update(Action::RecalculateChokes {
                random_seed: 999
            });

            let unchoked_count = state.peers.values()
                .filter(|p| p.am_choking == super::ChokeStatus::Unchoke)
                .count();

            // Even if everyone is slow, we MUST NOT unchoke more than slots + 1 (optimistic).
            // In a strict implementation, if everyone is 0, we might unchoke NO ONE (except optimistic),
            // or we might unchoke randoms. But we must never exceed the limit.
            prop_assert!(unchoked_count <= UPLOAD_SLOTS_DEFAULT + 1,
                "Too many peers unchoked in a snubbed swarm! Count: {}, Limit: {}", unchoked_count, UPLOAD_SLOTS_DEFAULT + 1);
        }

        // --- TEST 4: Rarest First Tiebreaker Invariant ---
        #[test]
        fn test_rarest_first_tie(mut state in rarest_first_tie_strategy()) {

            let effects = state.update(Action::AssignWork { peer_id: "target_peer".into() });

            let picked_idx = effects.iter().find_map(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                        return reqs.first().map(|(idx, _, _)| *idx);
                    }
                }
                None
            });

            if let Some(idx) = picked_idx {
                // It must be one of the available pieces (0 or 1).
                // A stable sort usually picks the lower index (0).
                // A random sort picks either. Both are valid "Rarest First" outcomes for a tie.
                prop_assert!(idx == 0 || idx == 1,
                    "Tiebreaker failed! Picked {}, expected 0 or 1.", idx);
            } else {
                prop_assert!(false, "Tiebreaker caused deadlock: No piece requested!");
            }
        }

        // --- TEST 5: Integrated Logic (The "Choke Check") ---
        #[test]
        fn test_choke_during_pick(mut state in combined_algo_strategy()) {

            let _ = state.update(Action::RecalculateChokes {  random_seed: 42 });

            let effects = state.update(Action::AssignWork { peer_id: "medium_both".into() });

            // The request should be valid regardless of OUR choking status towards them.
            // (BitTorrent allows downloading from people we choke, though they might not like it).
            // However, we MUST verify we only request pieces they actually have.
            if let Some(Effect::SendToPeer { cmd, .. }) = effects.first() {
                if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                    if let Some((idx, _, _)) = reqs.first() {
                        let peer = state.peers.get("medium_both").unwrap();
                        // Invariant: We must never request a piece the peer doesn't have
                        prop_assert!(
                            peer.bitfield.get(*idx as usize) == Some(&true),
                            "Logic Error: Requested Piece {} which 'medium_both' does not have!",
                            idx
                        );
                    }
                }
            }
        }

        // --- TEST 6: Tit-for-Tat Justice (Hero vs Parasite) ---
        #[test]
        fn test_free_rider_justice(mut state in free_rider_strategy()) {

            // We set a fixed seed to control Optimistic Unchoke.
            // In a real scenario, the Parasite might get the Optimistic slot occasionally,
            // but the Regular slots MUST go to the Hero.
            // Since we only have 1 slot total in this strat, logic dictates Hero gets it.
            let _ = state.update(Action::RecalculateChokes {
                random_seed: 42
            });

            let hero = state.peers.get("hero_peer").unwrap();
            prop_assert_eq!(hero.am_choking.clone(), super::ChokeStatus::Unchoke,
                "Injustice! The Hero peer (high contributor) was choked.");

            let parasite = state.peers.get("parasite_peer").unwrap();
            // Note: If your Optimistic Unchoke logic overrides the single slot,
            // this assert might flake depending on the seed.
            // Ideally, regular slots > optimistic slots.
            prop_assert_eq!(parasite.am_choking.clone(), super::ChokeStatus::Choke,
                "Exploit! The Free-Rider (zero contributor) stole the upload slot.");
        }

        // --- TEST 8: Scale & Complexity ---
        #[test]
        fn test_rarest_first_scale(mut state in huge_swarm_strategy()) {

            let effects = state.update(Action::AssignWork { peer_id: "rare_peer".into() });

            let picked = effects.iter().any(|e| {
                if let Effect::SendToPeer { cmd, .. } = e {
                    if let TorrentCommand::BulkRequest(ref reqs) = **cmd {
                        return reqs.iter().any(|(idx, _, _)| *idx == 0);
                    }
                }
                false
            });

            prop_assert!(picked, "Scale test failed: Did not pick the only available piece (0) from the rare peer.");
        }

        // --- TEST 9: Choke Race Condition (The "Stop" Check) ---
        #[test]
        fn test_choke_race_condition(mut state in combined_algo_strategy()) {

            state.update(Action::PeerUnchoked { peer_id: "medium_both".into() });

            state.update(Action::PeerChoked { peer_id: "medium_both".into() });

            let effects = state.update(Action::AssignWork { peer_id: "medium_both".into() });

            // If we are choked, we must NOT send a Request, even if we want the data.
            let sent_request = effects
                .iter()
                .any(|e| matches!(e, Effect::SendToPeer { cmd, .. } if matches!(**cmd, TorrentCommand::BulkRequest(_))));

            prop_assert!(!sent_request, "Race Condition Fail: Requested data while Choked!");
        }

    }

    // STATE MACHINE FUZZER (Expanded Lifecycle Coverage)

    mod state_machine {
        use super::*;
        use super::{inject_network_faults, inject_reordering_faults};
        use crate::torrent_manager::state::tests::create_dummy_torrent;
        use proptest_state_machine::{ReferenceStateMachine, StateMachineTest};
        use std::collections::HashSet;

        // --- 1. THE MODEL ---
        #[derive(Clone, Debug)]
        pub struct TorrentModel {
            pub connected_peers: HashSet<String>,
            pub total_pieces: u32,
            pub paused: bool,
            pub status: TorrentStatus,
            pub has_metadata: bool,
            pub downloaded_pieces: HashSet<u32>,
        }

        impl TorrentModel {
            fn new_file(pieces: u32) -> Self {
                Self {
                    connected_peers: HashSet::new(),
                    total_pieces: pieces,
                    paused: false,
                    status: TorrentStatus::Validating,
                    has_metadata: true,
                    downloaded_pieces: HashSet::new(),
                }
            }

            fn new_magnet(pieces: u32) -> Self {
                Self {
                    connected_peers: HashSet::new(),
                    total_pieces: pieces,
                    paused: false,
                    status: TorrentStatus::AwaitingMetadata,
                    has_metadata: false,
                    downloaded_pieces: HashSet::new(),
                }
            }
        }

        // --- 2. THE REFERENCE MACHINE ---
        impl ReferenceStateMachine for TorrentModel {
            type State = Self;
            type Transition = Action;

            fn init_state() -> BoxedStrategy<Self::State> {
                prop_oneof![
                    Just(TorrentModel::new_file(5)),
                    Just(TorrentModel::new_magnet(5))
                ]
                .boxed()
            }

            fn transitions(state: &Self::State) -> BoxedStrategy<Self::Transition> {
                let mut strategies = vec![
                    Just(Action::Tick { dt_ms: 1000 }).boxed(),
                    Just(Action::Cleanup).boxed(),
                    Just(Action::FatalError).boxed(),
                    Just(Action::Shutdown).boxed(),
                    Just(Action::Delete).boxed(),
                    Just(Action::ConnectToWebSeeds).boxed(),
                ];

                // ... (Re-Init, Pause/Resume, Metadata, Phase Transitions logic unchanged) ...
                strategies.push(
                    any::<bool>()
                        .prop_map(|paused| Action::TorrentManagerInit {
                            is_paused: paused,
                            announce_immediately: !paused,
                        })
                        .boxed(),
                );

                if state.paused {
                    strategies.push(Just(Action::Resume).boxed());
                } else {
                    strategies.push(Just(Action::Pause).boxed());
                }

                if state.status == TorrentStatus::AwaitingMetadata {
                    strategies.push(
                        Just(Action::MetadataReceived {
                            torrent: Box::new(create_dummy_torrent(state.total_pieces as usize)),
                            metadata_length: (state.total_pieces * 16384) as i64,
                        })
                        .boxed(),
                    );
                }

                if state.status == TorrentStatus::Validating {
                    let max_pieces = state.total_pieces;
                    strategies.push(
                        proptest::collection::vec(0..max_pieces, 0..max_pieces as usize)
                            .prop_map(|pieces| Action::ValidationComplete {
                                completed_pieces: pieces,
                            })
                            .boxed(),
                    );
                }

                if state.status == TorrentStatus::Standard || state.status == TorrentStatus::Endgame
                {
                    strategies.push(Just(Action::CheckCompletion).boxed());
                }

                // Connection Actions
                // -> FIX HERE: Ensure we don't generate empty peer IDs
                strategies.push(
                    proptest::string::string_regex(".+")
                        .unwrap()
                        .prop_map(|id| Action::PeerSuccessfullyConnected { peer_id: id })
                        .boxed(),
                );

                // Peer Interaction (unchanged logic, selects from existing peers)
                if !state.connected_peers.is_empty() && state.has_metadata {
                    let peer_strategy =
                        prop::sample::select(Vec::from_iter(state.connected_peers.clone()));
                    // ... (rest of peer interaction logic)
                    let piece_strategy = 0..state.total_pieces;

                    strategies.push(
                        peer_strategy
                            .clone()
                            .prop_map(|id| Action::PeerDisconnected {
                                peer_id: id,
                                force: true,
                            })
                            .boxed(),
                    );
                    strategies.push(
                        peer_strategy
                            .clone()
                            .prop_map(|id| Action::PeerUnchoked { peer_id: id })
                            .boxed(),
                    );

                    if state.status != TorrentStatus::Validating
                        && state.status != TorrentStatus::AwaitingMetadata
                    {
                        strategies.push(
                            (peer_strategy.clone(), piece_strategy.clone())
                                .prop_map(|(id, idx)| Action::PeerHavePiece {
                                    peer_id: id,
                                    piece_index: idx,
                                })
                                .boxed(),
                        );

                        strategies.push(
                            peer_strategy
                                .clone()
                                .prop_map(|id| Action::AssignWork { peer_id: id })
                                .boxed(),
                        );

                        strategies.push(
                            (
                                peer_strategy.clone(),
                                piece_strategy.clone(),
                                any::<u32>(),
                                prop::collection::vec(any::<u8>(), 1..1024),
                            )
                                .prop_map(|(id, idx, offset, data)| Action::IncomingBlock {
                                    peer_id: id,
                                    piece_index: idx,
                                    block_offset: offset,
                                    data,
                                })
                                .boxed(),
                        );

                        strategies.push(
                            (peer_strategy.clone(), piece_strategy.clone())
                                .prop_map(|(id, idx)| Action::PieceWrittenToDisk {
                                    peer_id: id,
                                    piece_index: idx,
                                })
                                .boxed(),
                        );
                    }
                }

                prop::strategy::Union::new(strategies).boxed()
            }

            fn apply(mut state: Self::State, trans: &Self::Transition) -> Self::State {
                match trans {
                    Action::PeerSuccessfullyConnected { peer_id } => {
                        state.connected_peers.insert(peer_id.clone());
                    }
                    Action::PeerDisconnected {
                        peer_id,
                        force: true,
                    } => {
                        state.connected_peers.remove(peer_id);
                    }
                    Action::Pause | Action::FatalError => {
                        state.paused = true;
                        state.connected_peers.clear();
                    }
                    Action::Resume => {
                        state.paused = false;
                    }
                    Action::TorrentManagerInit { is_paused, .. } => {
                        state.paused = *is_paused;
                    }
                    Action::Shutdown => {
                        state.paused = true;
                        state.connected_peers.clear();
                    }
                    Action::Delete => {
                        state.paused = true;
                        state.connected_peers.clear();
                        state.downloaded_pieces.clear(); // Clear model tracking
                        if state.has_metadata {
                            state.status = TorrentStatus::Validating;
                        } else {
                            state.status = TorrentStatus::AwaitingMetadata;
                        }
                    }

                    Action::MetadataReceived { .. } if !state.has_metadata => {
                        state.has_metadata = true;
                        state.status = TorrentStatus::Validating;
                        state.downloaded_pieces.clear();
                    }

                    Action::ValidationComplete { completed_pieces }
                        if state.status == TorrentStatus::Validating =>
                    {
                        state.status = TorrentStatus::Standard;
                        for p in completed_pieces {
                            state.downloaded_pieces.insert(*p);
                        }
                        // Check for immediate completion
                        if state.downloaded_pieces.len() as u32 == state.total_pieces {
                            state.status = TorrentStatus::Done;
                        }
                    }

                    Action::PieceWrittenToDisk { piece_index, .. }
                        if matches!(
                            state.status,
                            TorrentStatus::Standard | TorrentStatus::Endgame
                        ) =>
                    {
                        // FIX: Model now mimics SUT's completion logic
                        state.downloaded_pieces.insert(*piece_index);
                        if state.downloaded_pieces.len() as u32 == state.total_pieces {
                            state.status = TorrentStatus::Done;
                        }
                    }

                    _ => {}
                }
                state
            }
        }

        // --- 3. THE BINDING ---
        impl StateMachineTest for TorrentModel {
            type SystemUnderTest = TorrentState;
            type Reference = TorrentModel;

            fn init_test(ref_state: &TorrentModel) -> Self::SystemUnderTest {
                let (torrent, status) = if ref_state.has_metadata {
                    (
                        Some(create_dummy_torrent(ref_state.total_pieces as usize)),
                        TorrentStatus::Validating,
                    )
                } else {
                    (None, TorrentStatus::AwaitingMetadata)
                };

                let piece_manager = if ref_state.has_metadata {
                    let mut pm = PieceManager::new();
                    pm.set_initial_fields(ref_state.total_pieces as usize, false);
                    pm
                } else {
                    PieceManager::new()
                };

                TorrentState {
                    torrent,
                    torrent_status: status,
                    is_paused: ref_state.paused,
                    piece_manager,
                    torrent_data_path: Some(PathBuf::from("/tmp/fuzz")),
                    ..Default::default()
                }
            }

            fn apply(
                mut sut: Self::SystemUnderTest,
                ref_state: &TorrentModel,
                transition: Action,
            ) -> Self::SystemUnderTest {
                if let Action::PeerSuccessfullyConnected { peer_id } = &transition {
                    if !sut.peers.contains_key(peer_id) {
                        let (tx, _) = tokio::sync::mpsc::channel(1);
                        let mut peer = PeerState::new(peer_id.clone(), tx, sut.now);
                        peer.peer_id = peer_id.as_bytes().to_vec();
                        sut.peers.insert(peer_id.clone(), peer);
                        sut.number_of_successfully_connected_peers = sut.peers.len();
                    }
                }

                let _ = sut.update(transition.clone());

                // Advance Model to Post-State for comparison
                let expected_state =
                    <TorrentModel as ReferenceStateMachine>::apply(ref_state.clone(), &transition);

                // Metadata Integrity
                assert_eq!(
                    sut.torrent.is_some(),
                    expected_state.has_metadata,
                    "SUT Metadata existence mismatch!"
                );

                // Status Sync
                let sut_status_norm = if sut.torrent_status == TorrentStatus::Endgame {
                    TorrentStatus::Standard
                } else {
                    sut.torrent_status.clone()
                };

                let model_status_norm = if expected_state.status == TorrentStatus::Endgame {
                    TorrentStatus::Standard
                } else {
                    expected_state.status.clone()
                };

                assert_eq!(
                    sut_status_norm,
                    model_status_norm,
                    "Status Mismatch! SUT: {:?} (Normalized), Model: {:?} (Normalized). Action: {:?}",
                    sut.torrent_status, expected_state.status, transition
                );

                // Peer Count Sync
                if !matches!(transition, Action::Cleanup) {
                    assert_eq!(
                        sut.peers.len(),
                        expected_state.connected_peers.len(),
                        "Model/SUT Peer Mismatch! \nModel: {:?}\nSUT: {:?}",
                        expected_state.connected_peers,
                        sut.peers.keys()
                    );
                }

                sut
            }
        }

        // --- 4. THE RUNNER ---
        proptest! {
            #![proptest_config(ProptestConfig::default())]

            #[test]
            fn test_lifecycle_state_machine(
                (initial_state, transitions, tracker) in TorrentModel::sequential_strategy(20)
            ) {
                TorrentModel::test_sequential(
                    proptest::test_runner::Config::default(),
                    initial_state,
                    transitions,
                    tracker
                );
            }

            #[test]
            fn test_state_machine_network_faults(
                (initial_state, clean_actions, _) in TorrentModel::sequential_strategy(20),
                fault_entropy in proptest::collection::vec(any::<u8>(), 50)
            ) {
                let faulty_actions = inject_network_faults(clean_actions, fault_entropy);
                let mut ref_state = initial_state.clone();
                let mut sut = TorrentModel::init_test(&ref_state);

                for action in faulty_actions {
                    // Clone SUT to keep ownership valid for the next iteration if check passes
                    let sut_clone = sut.clone();

                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        <TorrentModel as StateMachineTest>::apply(sut_clone, &ref_state, action.clone())
                    }));

                    match result {
                        Ok(new_sut) => {
                            sut = new_sut;
                            // Advance the Reference Model
                            ref_state = <TorrentModel as ReferenceStateMachine>::apply(ref_state, &action);

                            // The SUT removes peers based on internal timers/logic the Model doesn't have.
                            // To prevent desync on the *next* action (like Tick), we adopt the SUT's
                            // peer list as the new truth.
                            if matches!(action, Action::Cleanup) {
                                ref_state.connected_peers = sut.peers.keys().cloned().collect();
                            }
                        }
                        Err(_) => { panic!("SUT Panicked during Network Fault Injection!\nAction: {:?}", action); }
                    }
                }
            }

            #[test]
            fn test_state_machine_network_reordering(
                (initial_state, clean_actions, _) in TorrentModel::sequential_strategy(20),
                seed in any::<u64>()
            ) {
                let chaotic_actions = inject_reordering_faults(clean_actions, seed);
                let mut ref_state = initial_state.clone();
                let mut sut = TorrentModel::init_test(&ref_state);

                for action in chaotic_actions {
                    let sut_clone = sut.clone();
                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        <TorrentModel as StateMachineTest>::apply(sut_clone, &ref_state, action.clone())
                    }));

                    match result {
                        Ok(new_sut) => {
                            sut = new_sut;
                            ref_state = <TorrentModel as ReferenceStateMachine>::apply(ref_state, &action);

                            if matches!(action, Action::Cleanup) {
                                ref_state.connected_peers = sut.peers.keys().cloned().collect();
                            }
                        }
                        Err(_) => { panic!("SUT Panicked during Network Reordering!\nAction: {:?}", action); }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod integration_tests {
    use crate::config::Settings;
    use sha1::{Digest, Sha1};
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::{broadcast, mpsc, watch};
    // Correct Import for the client struct
    use crate::resource_manager::{ResourceManager, ResourceManagerClient};
    use crate::token_bucket::TokenBucket;
    use crate::torrent_file::Torrent;
    use crate::torrent_manager::{
        ManagerCommand, TorrentManager, TorrentMetrics, TorrentParameters,
    };

    fn full_bitfield(num_pieces: usize) -> Vec<u8> {
        let mut bf = vec![0u8; num_pieces.div_ceil(8)];
        for i in 0..num_pieces {
            let byte_idx = i / 8;
            let bit_idx = 7 - (i % 8);
            bf[byte_idx] |= 1 << bit_idx;
        }
        bf
    }

    fn create_manager_harness(
        name: &str,
        num_pieces: usize,
        piece_size: usize,
        temp_dir: std::path::PathBuf,
    ) -> (
        TorrentManager,
        mpsc::Sender<ManagerCommand>,
        ResourceManagerClient,
    ) {
        let (_incoming_tx, incoming_peer_rx) = mpsc::channel(100);
        let (cmd_tx, cmd_rx) = mpsc::channel(100);

        // Event Drainer
        let (event_tx, mut event_rx) = mpsc::channel(500);
        tokio::spawn(async move { while event_rx.recv().await.is_some() {} });

        let (metrics_tx, _) = watch::channel(TorrentMetrics::default());
        let (shutdown_tx, _) = broadcast::channel(1);

        let settings_val = Settings {
            client_id: "-SS0001-TESTTESTTEST".to_string(),
            ..Default::default()
        };
        let settings = Arc::new(settings_val);

        let mut limits = HashMap::new();
        limits.insert(
            crate::resource_manager::ResourceType::PeerConnection,
            (1000, 1000),
        );
        limits.insert(
            crate::resource_manager::ResourceType::DiskRead,
            (1000, 1000),
        );
        limits.insert(
            crate::resource_manager::ResourceType::DiskWrite,
            (1000, 1000),
        );
        limits.insert(crate::resource_manager::ResourceType::Reserve, (0, 0));

        let (resource_manager, rm_client) = ResourceManager::new(limits, shutdown_tx.clone());
        tokio::spawn(resource_manager.run());

        let bucket = Arc::new(TokenBucket::new(f64::INFINITY, f64::INFINITY));

        let single_piece_hash = Sha1::digest(vec![0xAA; piece_size]).to_vec();
        let mut all_hashes = Vec::new();
        for _ in 0..num_pieces {
            all_hashes.extend_from_slice(&single_piece_hash);
        }

        let total_len = (num_pieces * piece_size) as i64;

        let torrent = Torrent {
            announce: None,
            announce_list: None,
            url_list: None,
            info: crate::torrent_file::Info {
                name: name.to_string(),
                piece_length: piece_size as i64,
                pieces: all_hashes,
                length: total_len,
                files: vec![],
                private: None,
                md5sum: None,
                meta_version: None,
                file_tree: None,
            },
            info_dict_bencode: vec![0u8; 20],
            created_by: None,
            creation_date: None,
            encoding: None,
            comment: None,
            piece_layers: None,
        };

        let params = TorrentParameters {
            dht_handle: {
                #[cfg(feature = "dht")]
                {
                    mainline::Dht::builder().port(0).build().unwrap().as_async()
                }
                #[cfg(not(feature = "dht"))]
                {
                    ()
                }
            },
            incoming_peer_rx,
            metrics_tx,
            torrent_validation_status: false,
            torrent_data_path: Some(temp_dir),
            container_name: None,
            manager_command_rx: cmd_rx,
            manager_event_tx: event_tx,
            settings,
            resource_manager: rm_client.clone(),
            global_dl_bucket: bucket.clone(),
            global_ul_bucket: bucket,
            file_priorities: HashMap::new(),
        };

        (
            TorrentManager::from_torrent(params, torrent).unwrap(),
            cmd_tx,
            rm_client,
        )
    }

    async fn spawn_mock_peer(
        manager: &mut TorrentManager,
        bitfield: Vec<u8>,
        upload_delay: std::time::Duration,
    ) -> (mpsc::Receiver<Vec<u8>>, mpsc::Sender<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let peer_addr = listener.local_addr().unwrap();

        manager.connect_to_peer(peer_addr);

        let (tx_events, rx_events) = mpsc::channel(100);
        let (tx_ctrl, mut rx_ctrl) = mpsc::channel(1);

        tokio::spawn(async move {
            if let Ok((socket, _)) = listener.accept().await {
                let (mut rd, mut wr) = socket.into_split();

                let mut handshake_buf = vec![0u8; 68];
                if rd.read_exact(&mut handshake_buf).await.is_err() {
                    return;
                }

                let mut h_resp = vec![0u8; 68];
                h_resp[0] = 19;
                h_resp[1..20].copy_from_slice(b"BitTorrent protocol");
                h_resp[28..48].copy_from_slice(&handshake_buf[28..48]);
                let _ = wr.write_all(&h_resp).await;

                let mut msg = Vec::new();
                msg.extend_from_slice(&(1 + bitfield.len() as u32).to_be_bytes());
                msg.push(5);
                msg.extend_from_slice(&bitfield);
                let _ = wr.write_all(&msg).await;

                // This ensures the Manager knows we want data, so it considers Unchoking us.
                let interested_msg = vec![0, 0, 0, 1, 2];
                let _ = wr.write_all(&interested_msg).await;

                let mut buf = vec![0u8; 4096];
                let mut buffer = Vec::new();
                let mut am_choking = true;

                loop {
                    tokio::select! {
                        _ = rx_ctrl.recv() => break,
                        res = rd.read(&mut buf) => {
                            match res {
                                Ok(n) if n > 0 => buffer.extend_from_slice(&buf[..n]),
                                _ => break,
                            }
                        }
                    }

                    while buffer.len() >= 4 {
                        let len = u32::from_be_bytes(buffer[0..4].try_into().unwrap()) as usize;
                        if buffer.len() < 4 + len {
                            break;
                        }

                        let msg_frame = &buffer[4..4 + len];
                        if !msg_frame.is_empty() {
                            match msg_frame[0] {
                                0 => {
                                    let _ = tx_events.try_send(vec![0]);
                                }
                                1 => {
                                    let _ = tx_events.try_send(vec![1]);
                                }
                                2 if am_choking => {
                                    // Interested
                                    let _ = wr.write_all(&[0, 0, 0, 1, 1]).await;
                                    am_choking = false;
                                }
                                6 => {
                                    // Request
                                    let index =
                                        u32::from_be_bytes(msg_frame[1..5].try_into().unwrap());
                                    let begin =
                                        u32::from_be_bytes(msg_frame[5..9].try_into().unwrap());
                                    let req_len =
                                        u32::from_be_bytes(msg_frame[9..13].try_into().unwrap());

                                    let mut rep = vec![6];
                                    rep.extend_from_slice(&index.to_be_bytes());
                                    rep.extend_from_slice(&begin.to_be_bytes());
                                    rep.extend_from_slice(&req_len.to_be_bytes());
                                    let _ = tx_events.try_send(rep);

                                    if upload_delay.as_millis() > 0 {
                                        tokio::time::sleep(upload_delay).await;
                                    }

                                    let data = vec![0xAA; req_len as usize];
                                    let total_len = 9 + req_len;
                                    let mut resp = Vec::new();
                                    resp.extend_from_slice(&total_len.to_be_bytes());
                                    resp.push(7);
                                    resp.extend_from_slice(&index.to_be_bytes());
                                    resp.extend_from_slice(&begin.to_be_bytes());
                                    resp.extend_from_slice(&data);
                                    let _ = wr.write_all(&resp).await;
                                }
                                8 => {
                                    // Cancel
                                    let index =
                                        u32::from_be_bytes(msg_frame[1..5].try_into().unwrap());
                                    let begin =
                                        u32::from_be_bytes(msg_frame[5..9].try_into().unwrap());
                                    let req_len =
                                        u32::from_be_bytes(msg_frame[9..13].try_into().unwrap());
                                    let mut rep = vec![8];
                                    rep.extend_from_slice(&index.to_be_bytes());
                                    rep.extend_from_slice(&begin.to_be_bytes());
                                    rep.extend_from_slice(&req_len.to_be_bytes());
                                    let _ = tx_events.try_send(rep);
                                }
                                _ => {}
                            }
                        }
                        buffer.drain(0..4 + len);
                    }
                }
            }
        });
        (rx_events, tx_ctrl)
    }

    #[tokio::test]
    async fn test_case_06_rarest_first_strategy() {
        let temp_dir = std::env::temp_dir().join("superseedr_rarest_first");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 2;
        let piece_size = 16_384;

        let (mut manager, _cmd, _res) =
            create_manager_harness("RarestFirst", num_pieces, piece_size, temp_dir.clone());

        // Peer A: Has [0, 1] (0xC0) - Rare Piece 1 holder
        let (mut rx_a, _k_a) = spawn_mock_peer(
            &mut manager,
            vec![0xC0],
            std::time::Duration::from_millis(0),
        )
        .await;
        // Peer B: Has [0] (0x80)
        let (mut rx_b, _k_b) = spawn_mock_peer(
            &mut manager,
            vec![0x80],
            std::time::Duration::from_millis(0),
        )
        .await;
        // Peer C: Has [0] (0x80)
        let (mut rx_c, _k_c) = spawn_mock_peer(
            &mut manager,
            vec![0x80],
            std::time::Duration::from_millis(0),
        )
        .await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let start = std::time::Instant::now();
        let mut rare_piece_requested = false;

        while start.elapsed() < std::time::Duration::from_secs(5) {
            tokio::select! {
                Some(msg) = rx_a.recv() => {
                    if msg.len() >= 5 && msg[0] == 6 {
                        let idx = u32::from_be_bytes(msg[1..5].try_into().unwrap());
                        if idx == 1 {
                            rare_piece_requested = true;
                            break;
                        }
                    }
                }
                Some(_) = rx_b.recv() => {},
                Some(_) = rx_c.recv() => {},
                else => break,
            }
        }

        assert!(
            rare_piece_requested,
            "FAILED: Manager did not prioritize requesting Rare Piece 1 from Peer A!"
        );
        println!("SUCCESS: Rarest First - Peer A received request for rare piece 1.");

        let _ = _cmd.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[tokio::test]
    async fn test_case_08_full_swarm_1000_blocks() {
        let temp_dir = std::env::temp_dir().join("superseedr_full_swarm");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 1000;
        let piece_size = 16_384;
        let (mut manager, _cmd, _res) =
            create_manager_harness("FullSwarm", num_pieces, piece_size, temp_dir.clone());

        let make_bitfield = |pattern: fn(usize) -> bool| -> Vec<u8> {
            let mut bf = vec![0u8; num_pieces.div_ceil(8)];
            for i in 0..num_pieces {
                if pattern(i) {
                    let byte_idx = i / 8;
                    let bit_idx = 7 - (i % 8);
                    bf[byte_idx] |= 1 << bit_idx;
                }
            }
            bf
        };

        // Peer 1: SEEDER (Has All)
        let bf_seed = make_bitfield(|_| true);
        spawn_mock_peer(&mut manager, bf_seed, std::time::Duration::from_millis(1)).await;

        // Peer 2: FIRST HALF (Has 0-499)
        let bf_first = make_bitfield(|i| i < 500);
        spawn_mock_peer(&mut manager, bf_first, std::time::Duration::from_millis(2)).await;

        // Peer 3: SECOND HALF (Has 500-999)
        let bf_second = make_bitfield(|i| i >= 500);
        spawn_mock_peer(&mut manager, bf_second, std::time::Duration::from_millis(2)).await;

        // Peer 4: EVENS
        let bf_even = make_bitfield(|i| i % 2 == 0);
        spawn_mock_peer(&mut manager, bf_even, std::time::Duration::from_millis(5)).await;

        // Peer 5: ODDS
        let bf_odd = make_bitfield(|i| i % 2 != 0);
        spawn_mock_peer(&mut manager, bf_odd, std::time::Duration::from_millis(5)).await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let expected_size = (num_pieces * piece_size) as u64;
        let file_path = temp_dir.join("FullSwarm");

        let start = std::time::Instant::now();
        let timeout_duration = std::time::Duration::from_secs(45);
        let mut success = false;

        println!("Waiting for 1000 blocks (~16MB) from 5 peers...");

        while start.elapsed() < timeout_duration {
            if let Ok(meta) = std::fs::metadata(&file_path) {
                if meta.len() >= expected_size {
                    success = true;
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        }

        if !success {
            panic!("FAILED: Swarm download did not complete in 45s.");
        }

        println!(
            "SUCCESS: Downloaded 1000 blocks (~16MB) from 5 mixed peers in {:.2?}",
            start.elapsed()
        );

        let _ = _cmd.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn test_debug_pipeline_latency() {
        // SETUP
        let temp_dir = std::env::temp_dir().join("superseedr_latency_debug");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // 500 blocks * 16KB = ~8MB
        let num_pieces = 500;
        let piece_size = 16_384;
        let (mut manager, _cmd, _res) =
            create_manager_harness("LatencyTest", num_pieces, piece_size, temp_dir.clone());

        // Spawn 1 Peer with 50ms Latency (Simulating a real internet connection)
        let bf_all = vec![0xFFu8; num_pieces.div_ceil(8)];

        // 50ms delay per block write
        spawn_mock_peer(&mut manager, bf_all, std::time::Duration::from_millis(50)).await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        // MONITOR
        let start = std::time::Instant::now();
        let expected_size = (num_pieces * piece_size) as u64;
        let file_path = temp_dir.join("LatencyTest");

        let mut success = false;
        // Give it 10 seconds.
        // At 300KB/s (Broken Pipeline), 8MB takes ~26 seconds -> FAIL.
        // At 5MB/s (Working Pipeline), 8MB takes ~1.6 seconds -> PASS.
        while start.elapsed() < std::time::Duration::from_secs(10) {
            if let Ok(meta) = std::fs::metadata(&file_path) {
                if meta.len() >= expected_size {
                    success = true;
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }

        if !success {
            println!("❌ PIPELINE BROKEN: Transfer too slow for high latency peer.");
            println!("   Likely cause: 'inflight_requests' limit is too low or 'AssignWork' loop is exiting early.");
        } else {
            println!("✅ PIPELINE WORKING: High throughput achieved despite latency.");
        }

        let _ = _cmd.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(success);
    }

    #[tokio::test]
    async fn test_non_aligned_piece_length_small_swarm_completes() {
        let temp_dir = std::env::temp_dir().join("superseedr_non_aligned_20k");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 4;
        let piece_size = 20_000;
        let (mut manager, cmd_tx, _res) =
            create_manager_harness("NonAligned20k", num_pieces, piece_size, temp_dir.clone());

        let bf_all = full_bitfield(num_pieces);
        spawn_mock_peer(&mut manager, bf_all, std::time::Duration::from_millis(0)).await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let expected_size = (num_pieces * piece_size) as u64;
        let file_path = temp_dir.join("NonAligned20k");
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(12);
        let mut success = false;

        while start.elapsed() < timeout {
            if let Ok(meta) = std::fs::metadata(&file_path) {
                if meta.len() >= expected_size {
                    success = true;
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(
            success,
            "Non-aligned piece-length torrent failed to complete in bounded time"
        );
    }

    #[tokio::test]
    async fn test_tiny_piece_length_small_swarm_completes() {
        let temp_dir = std::env::temp_dir().join("superseedr_tiny_piece_1k");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 8;
        let piece_size = 1_024;
        let (mut manager, cmd_tx, _res) =
            create_manager_harness("TinyPiece1k", num_pieces, piece_size, temp_dir.clone());

        let bf_all = full_bitfield(num_pieces);
        spawn_mock_peer(&mut manager, bf_all, std::time::Duration::from_millis(0)).await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let expected_size = (num_pieces * piece_size) as u64;
        let file_path = temp_dir.join("TinyPiece1k");
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(12);
        let mut success = false;

        while start.elapsed() < timeout {
            if let Ok(meta) = std::fs::metadata(&file_path) {
                if meta.len() >= expected_size {
                    success = true;
                    break;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(
            success,
            "Tiny piece-length torrent failed to complete in bounded time"
        );
    }

    fn decode_triplet_event(msg: &[u8], expected_kind: u8) -> Option<(u32, u32, u32)> {
        if msg.len() < 13 || msg[0] != expected_kind {
            return None;
        }
        let idx = u32::from_be_bytes(msg[1..5].try_into().ok()?);
        let begin = u32::from_be_bytes(msg[5..9].try_into().ok()?);
        let len = u32::from_be_bytes(msg[9..13].try_into().ok()?);
        Some((idx, begin, len))
    }

    #[tokio::test]
    async fn test_non_aligned_request_identity_emits_piece_local_requests() {
        let temp_dir = std::env::temp_dir().join("superseedr_req_identity_non_aligned");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 2;
        let piece_size = 20_000;
        let (mut manager, cmd_tx, _res) = create_manager_harness(
            "ReqIdentityNonAligned",
            num_pieces,
            piece_size,
            temp_dir.clone(),
        );

        let (mut rx_events, _ctrl) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(0),
        )
        .await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(5);
        let mut reqs = Vec::new();

        while start.elapsed() < timeout && reqs.len() < 4 {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(200), rx_events.recv()).await
            {
                if let Some(t) = decode_triplet_event(&msg, 6) {
                    reqs.push(t);
                }
            }
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(!reqs.is_empty(), "Expected request tuples from peer");
        let piece0: Vec<(u32, u32)> = reqs
            .iter()
            .filter(|(idx, _, _)| *idx == 0)
            .map(|(_, begin, len)| (*begin, *len))
            .collect();
        let piece1: Vec<(u32, u32)> = reqs
            .iter()
            .filter(|(idx, _, _)| *idx == 1)
            .map(|(_, begin, len)| (*begin, *len))
            .collect();

        assert!(
            !piece0.is_empty() && !piece1.is_empty(),
            "Expected requests for both pieces, got {:?}",
            reqs
        );
        assert!(
            piece0.contains(&(0, 16_384)) && piece0.contains(&(16_384, 3_616)),
            "Piece 0 requests must be piece-local for non-aligned geometry: {:?}",
            piece0
        );
        assert!(
            piece1.contains(&(0, 16_384)) && piece1.contains(&(16_384, 3_616)),
            "Piece 1 requests must be piece-local for non-aligned geometry: {:?}",
            piece1
        );
    }

    #[tokio::test]
    async fn test_aligned_request_identity_emits_piece_local_requests() {
        let temp_dir = std::env::temp_dir().join("superseedr_req_identity_aligned");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 2;
        let piece_size = 16_384;
        let (mut manager, cmd_tx, _res) = create_manager_harness(
            "ReqIdentityAligned",
            num_pieces,
            piece_size,
            temp_dir.clone(),
        );

        let (mut rx_events, _ctrl) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(0),
        )
        .await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(5);
        let mut reqs = Vec::new();

        while start.elapsed() < timeout && reqs.len() < 2 {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(200), rx_events.recv()).await
            {
                if let Some(t) = decode_triplet_event(&msg, 6) {
                    reqs.push(t);
                }
            }
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(
            reqs.contains(&(0, 0, 16_384)) && reqs.contains(&(1, 0, 16_384)),
            "Aligned requests must remain piece-local: {:?}",
            reqs
        );
    }

    #[tokio::test]
    async fn test_non_aligned_cancel_identity_emits_piece_local_cancels() {
        let temp_dir = std::env::temp_dir().join("superseedr_cancel_identity_non_aligned");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 1;
        let piece_size = 20_000;
        let (mut manager, cmd_tx, _res) = create_manager_harness(
            "CancelIdentityNonAligned",
            num_pieces,
            piece_size,
            temp_dir.clone(),
        );

        let (mut rx_slow, _ctrl_slow) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(120),
        )
        .await;
        let (_rx_fast, _ctrl_fast) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(10),
        )
        .await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let precondition_start = std::time::Instant::now();
        let precondition_timeout = std::time::Duration::from_secs(4);
        let mut slow_peer_requested_piece = false;
        while precondition_start.elapsed() < precondition_timeout {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(250), rx_slow.recv()).await
            {
                if decode_triplet_event(&msg, 6).is_some() {
                    slow_peer_requested_piece = true;
                    break;
                }
            }
        }

        assert!(
            slow_peer_requested_piece,
            "Precondition failed: slow peer never received a request tuple"
        );

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(8);
        let mut cancels = Vec::new();

        while start.elapsed() < timeout {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(250), rx_slow.recv()).await
            {
                if let Some(t) = decode_triplet_event(&msg, 8) {
                    cancels.push(t);
                    if cancels.len() >= 2 {
                        break;
                    }
                }
            }
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(!cancels.is_empty(), "Expected at least one cancel tuple");
        assert!(
            cancels.iter().all(|(idx, _, _)| *idx == 0),
            "Cancels must stay in piece-local namespace for non-aligned case: {:?}",
            cancels
        );
        assert!(
            cancels.contains(&(0, 0, 16_384)) || cancels.contains(&(0, 16_384, 3_616)),
            "Expected non-aligned piece-local cancel tuples, got {:?}",
            cancels
        );
    }

    #[tokio::test]
    async fn test_aligned_cancel_identity_emits_piece_local_cancels() {
        let temp_dir = std::env::temp_dir().join("superseedr_cancel_identity_aligned");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let num_pieces = 1;
        let piece_size = 16_384;
        let (mut manager, cmd_tx, _res) = create_manager_harness(
            "CancelIdentityAligned",
            num_pieces,
            piece_size,
            temp_dir.clone(),
        );

        let (mut rx_slow, _ctrl_slow) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(120),
        )
        .await;
        let (_rx_fast, _ctrl_fast) = spawn_mock_peer(
            &mut manager,
            full_bitfield(num_pieces),
            std::time::Duration::from_millis(10),
        )
        .await;

        let manager_handle = tokio::spawn(async move {
            let _ = manager.run(false).await;
        });

        let precondition_start = std::time::Instant::now();
        let precondition_timeout = std::time::Duration::from_secs(4);
        let mut slow_peer_requested_piece = false;
        while precondition_start.elapsed() < precondition_timeout {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(250), rx_slow.recv()).await
            {
                if decode_triplet_event(&msg, 6).is_some() {
                    slow_peer_requested_piece = true;
                    break;
                }
            }
        }

        assert!(
            slow_peer_requested_piece,
            "Precondition failed: slow peer never received a request tuple"
        );

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(8);
        let mut cancels = Vec::new();

        while start.elapsed() < timeout {
            if let Ok(Some(msg)) =
                tokio::time::timeout(std::time::Duration::from_millis(250), rx_slow.recv()).await
            {
                if let Some(t) = decode_triplet_event(&msg, 8) {
                    cancels.push(t);
                    break;
                }
            }
        }

        let _ = cmd_tx.send(ManagerCommand::Shutdown).await;
        let _ = manager_handle.await;
        let _ = std::fs::remove_dir_all(temp_dir);

        assert!(
            cancels.contains(&(0, 0, 16_384)),
            "Aligned cancel must use exact piece-local tuple: {:?}",
            cancels
        );
    }
}