nanalogue 0.1.9

BAM/Mod BAM parsing and analysis tool with a single-molecule focus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
//! # Write Simulated Mod BAM
//! Generates simulated BAM files with base modifications for testing purposes.
//! Accepts JSON configuration to produce both BAM and FASTA reference files.
//! Please note that both BAM files and FASTA files are created from scratch,
//! so please do not specify pre-existing BAM or FASTA files in the output
//! path; if so, they will be overwritten.
//!
//! ## Example Usage
//!
//! We've shown how to construct `SimulationConfig` which contains input options
//! and then use it to create a BAM file below. You can also use [`SimulationConfigBuilder`]
//! to achieve this without using a `json` structure. Some of the fields in the `json` entry
//! shown below are optional; please read the comments following it.
//!
//! ```
//! use nanalogue_core::{Error, SimulationConfig, simulate_mod_bam::run};
//! use uuid::Uuid;
//!
//! let config_json = r#"{
//!   "contigs": {
//!     "number": 4,
//!     "len_range": [1000, 8000],
//!     "repeated_seq": "ATCGAATT"
//!   },
//!   "reads": [{
//!     "number": 1000,
//!     "mapq_range": [10, 20],
//!     "base_qual_range": [10, 20],
//!     "len_range": [0.1, 0.8],
//!     "barcode": "ACGTAA",
//!     "delete": [0.5, 0.7],
//!     "insert_middle": "ATCG",
//!     "mismatch": 0.5,
//!     "mods": [{
//!         "base": "T",
//!         "is_strand_plus": true,
//!         "mod_code": "T",
//!         "win": [4, 5],
//!         "mod_range": [[0.1, 0.2], [0.3, 0.4]]
//!     }]
//!   }],
//!   "seed": 42
//! }"#;
//!
//! // Note: * We generate four contigs `4` with a length chosen randomly from the range `1000-8000`
//! //         in the example above. Contigs are called `contig_00000`, ..., `contig_00003`.
//! //       * "repeated_seq" field is optional in contigs; if set, contigs are made by
//! //         repeating this sequence instead of generating random sequences.
//! //       * Reads are generated with options shown. In the example, 1000 reads are made, with a
//! //         mapping quality in the range 10-20, a basecalling quality in the range 10-20,
//! //         lengths in the range 10%-80% of a contig (each read is mapped to a contig chosen
//! //         randomly with equal probability for all contigs). Reads are randomly assigned to be
//! //         in one of seven states -> primary/secondary/supplementary X fwd/rev plus unmapped.
//! //         Read sequences are drawn from the associated contig at a random location.
//! //         (Unmapped reads are also drawn from contig sequences; they are just marked unmapped
//! //          after the fact).
//! //         Read names are 'n.uuid' where n is the read group number and uuid is a random UUID
//! //         (UUID is a random string that looks like this for example ->
//! //          "e9529f28-d27a-497a-be7e-bffdb77e8bc1"). Read group number is assigned
//! //         automatically, depending on how many entries are in the `reads` field.
//! //         In the example here, there is only one entry, so the read group number is 0,
//! //         so all the reads will have a name like '0.uuid'.
//! //       * "barcode" field is optional and can be omitted; barcodes added to both ends.
//! //         As sequences and lengths are generated independently of barcodes,
//! //         a barcode will _add_ 2 times so many bp to sequence length statistics.
//! //       * "delete" is optional. If specified, the shown section is deleted on
//! //         all reads. In the example, the section between the middle of the read (50%)
//! //         and seven-tenths of the read (70%) is deleted. The direction in the instructions
//! //         here is parallel to the reference genome.
//! //       * "insert_middle" is optional. If specified, the specified sequence will be inserted
//! //         at the middle of the read.
//! //       * "mismatch" is optional. If specified, this random fraction of bases is mismatched i.e.
//! //         we make the base different from what it is supposed to be.
//! //       * insertion/deletion/barcode are applied after sequence lengths are determined
//! //         according to the given options. In other words, these options will cause sequence
//! //         lengths to be different from the given statistics e.g. an insertion of
//! //         10 bp will make all reads longer than the desired sequence statistics by 10 bp.
//! //       * "mods" are optional as well, omitting them will create a BAM file
//! //          with no modification information.
//! //       * mod information is specified using windows i.e. in window of given size,
//! //         we enforce that mod probabilities per base are in the given range.
//! //         Multiple windows can be specified, and they repeat along the
//! //         read until it ends i.e. we cycle windows so we go 4Ts, 5Ts, 4Ts, 5Ts, ...
//! //         and probabilities are cycled as (0.1, 0.2), (0.3, 0.4), (0.1, 0.2), ...
//! //       * if windows and mod_range lists are of different sizes, the cycles may not line up.
//! //         e.g. if there are three window values and two mod ranges, then
//! //         windows repeat in cycles of 3 whereas mod ranges will repeat in cycles of 2.
//! //         You can use such inputs if this is what you want.
//! //       * "seed" is optional. If set, all random operations (contig generation, read
//! //         generation, modification placement, etc.) use a deterministic RNG seeded with
//! //         this value, producing identical output files across runs. If not set, the
//! //         simulation is non-reproducible.
//!
//! // Paths used here must not exist already as these are files created anew.
//! let config: SimulationConfig = serde_json::from_str(&config_json)?;
//! let temp_dir = std::env::temp_dir();
//! let bam_path = temp_dir.join(format!("{}.bam", Uuid::new_v4()));
//! let fasta_path = temp_dir.join(format!("{}.fa", Uuid::new_v4()));
//! let bai_path = bam_path.with_extension("bam.bai");
//! run(config, &bam_path, &fasta_path)?;
//! std::fs::remove_file(&bam_path)?;
//! std::fs::remove_file(&fasta_path)?;
//! std::fs::remove_file(&bai_path)?;
//! # Ok::<(), Error>(())
//! ```

use crate::{
    AllowedAGCTN, DNARestrictive, Error, F32Bw0and1, GetDNARestrictive, ModChar, OrdPair, ReadState,
};
use crate::{write_bam_denovo, write_fasta};
use derive_builder::Builder;
use itertools::join;
use rand::Rng;
use rand::SeedableRng as _;
use rand::rngs::StdRng;
use rand::seq::IteratorRandom as _;
use rust_htslib::bam;
use rust_htslib::bam::record::{Aux, Cigar, CigarString};
use serde::{Deserialize, Serialize};
use std::iter;
use std::num::{NonZeroU32, NonZeroU64};
use std::ops::RangeInclusive;
use std::path::Path;
use std::str::FromStr as _;
use uuid::Uuid;

/// We need a shorthand for this for a one-liner we use
/// in a macro provided by `derive_builder`.
type OF = OrdPair<F32Bw0and1>;

/// Creates an `OrdPair` of `F32Bw0and1` values
///
/// We do not export this macro as it involves `unwrap`,
/// so we only use it locally.
macro_rules! ord_pair_f32_bw0and1 {
    ($low:expr, $high:expr) => {
        OrdPair::new(
            F32Bw0and1::new($low).unwrap(),
            F32Bw0and1::new($high).unwrap(),
        )
        .unwrap()
    };
}

/// Main configuration struct for simulation.
///
/// After construction, you can pass it to [`crate::simulate_mod_bam::run`]
/// to create a mod BAM file. You can build this using [`SimulationConfigBuilder`]
/// as shown below.
///
/// # Example
///
/// Below struct can be used in appropriate routines to
/// create a BAM file.
///
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::{ContigConfigBuilder, SimulationConfigBuilder,
///     ReadConfigBuilder, ModConfigBuilder};
///
/// // Request two contigs with lengths randomly chosen from 1000 - 2000 bp.
/// let contig_config = ContigConfigBuilder::default()
///     .number(2)
///     .len_range((1000,2000)).build()?;
///
/// // First set of reads
/// let read_config1 = ReadConfigBuilder::default()
///     .number(100)
///     .mapq_range((10, 20))
///     .base_qual_range((30, 40))
///     .len_range((0.5, 0.6));
///
/// // second set of reads, now 200 requested with a modification and a barcode
/// let mod_config = ModConfigBuilder::default()
///     .base('C')
///     .is_strand_plus(true)
///     .mod_code("m".into())
///     .win(vec![2, 3])
///     .mod_range(vec![(0.1, 0.8), (0.3, 0.4)]).build()?;
///
/// let read_config2 = read_config1.clone()
///     .number(200)
///     .barcode("AATTG".into())
///     .mods(vec![mod_config]);
///
/// // set simulation config, ready to be fed into an appropriate function.
/// // .seed(42) makes the simulation reproducible; omit it for non-deterministic output.
/// let sim_config = SimulationConfigBuilder::default()
///     .contigs(contig_config)
///     .reads(vec![read_config1.build()?, read_config2.build()?])
///     .seed(42_u64)
///     .build()?;
/// # Ok::<(), Error>(())
/// ```
#[derive(Builder, Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
#[builder(default, build_fn(error = "Error"), pattern = "owned", derive(Clone))]
#[non_exhaustive]
pub struct SimulationConfig {
    /// Configuration for contig generation
    pub contigs: ContigConfig,
    /// Configuration for read generation
    pub reads: Vec<ReadConfig>,
    /// Seed for reproducible simulation. When set, all random operations
    /// use a deterministic RNG seeded with this value, producing identical
    /// output files across runs. If not set, simulation is non-reproducible.
    #[builder(setter(into, strip_option))]
    pub seed: Option<u64>,
}

/// Configuration for contig generation
///
/// The struct contains parameters which can then be passed to other
/// functions to construct the actual contig. Also refer to [`SimulationConfig`]
/// to see how this `struct` can be used, and [`ContigConfigBuilder`] for how
/// to build this (as shown below in the examples).
///
/// # Examples
///
/// Request two contigs with lengths randomly chosen from 1000 - 2000 bp.
/// The DNA of the contigs are randomly-generated.
///
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::ContigConfigBuilder;
///
/// let contig_config = ContigConfigBuilder::default()
///     .number(2)
///     .len_range((1000,2000)).build()?;
///
/// # Ok::<(), Error>(())
/// ```
///
/// Request similar contigs as above but with the DNA of the contigs
/// consisting of the same sequence repeated over and over.
///
/// ```
/// # use nanalogue_core::Error;
/// # use nanalogue_core::simulate_mod_bam::ContigConfigBuilder;
/// let contig_config = ContigConfigBuilder::default()
///     .number(2)
///     .len_range((1000,2000))
///     .repeated_seq("AAGCTTGA".into()).build()?;
///
/// # Ok::<(), Error>(())
/// ```
///
/// Request a contig with a fixed length and sequence.
/// As the repeated sequence's length is equal to the
/// contig length, and the contig length is precisely fixed,
/// you get a non-randomly generated contig.
///
/// ```
/// # use nanalogue_core::Error;
/// # use nanalogue_core::simulate_mod_bam::ContigConfigBuilder;
/// let contig_config = ContigConfigBuilder::default()
///     .number(1)
///     .len_range((20,20))
///     .repeated_seq("ACGTACGTACGTACGTACGT".into()).build()?;
///
/// # Ok::<(), Error>(())
/// ```
#[derive(Builder, Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
#[builder(default, build_fn(error = "Error"), pattern = "owned", derive(Clone))]
#[non_exhaustive]
pub struct ContigConfig {
    /// Number of contigs to generate
    #[builder(field(ty = "u32", build = "self.number.try_into()?"))]
    pub number: NonZeroU32,
    /// Contig length range in bp [min, max]
    #[builder(field(ty = "(u64, u64)", build = "self.len_range.try_into()?"))]
    pub len_range: OrdPair<NonZeroU64>,
    /// Optional repeated sequence to use for contigs instead of random generation
    #[builder(field(
        ty = "String",
        build = "(!self.repeated_seq.is_empty()).then(|| DNARestrictive::from_str(&self.repeated_seq)).transpose()?"
    ))]
    pub repeated_seq: Option<DNARestrictive>,
}

/// Configuration for read generation. Also refer to [`SimulationConfig`]
/// to see how this `struct` can be used, and to [`ReadConfigBuilder`] for
/// how to build this (as shown below in the examples).
///
/// # Example 1
///
///  Request reads without modifications
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::ReadConfigBuilder;
///
/// // First set of reads
/// let read_config1 = ReadConfigBuilder::default()
///     .number(100)
///     .mapq_range((10, 20))
///     .base_qual_range((30, 40))
///     .len_range((0.5, 0.6)).build()?;
///
/// # Ok::<(), Error>(())
/// ```
/// # Example 2
///
///  Request reads with modifications, but also with insertions, deletions, and a mismatch rate.
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::{ReadConfigBuilder, ModConfigBuilder};
///
/// let mod_config = ModConfigBuilder::default()
///     .base('C')
///     .is_strand_plus(true)
///     .mod_code("m".into())
///     .win(vec![2, 3])
///     .mod_range(vec![(0.1, 0.8), (0.3, 0.4)]).build()?;
///
/// let read_config2 = ReadConfigBuilder::default()
///     .number(200)
///     .mapq_range((30, 40))
///     .base_qual_range((50, 60))
///     .barcode("AATTG".into())
///     .len_range((0.7, 0.8))
///     .delete((0.2, 0.3))
///     .insert_middle("ATCGA".into())
///     .mismatch(0.1)
///     .mods(vec![mod_config]).build()?;
///
/// # Ok::<(), Error>(())
/// ```
#[derive(Builder, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[builder(default, build_fn(error = "Error"), pattern = "owned", derive(Clone))]
#[non_exhaustive]
pub struct ReadConfig {
    /// Total number of reads to generate
    #[builder(field(ty = "u32", build = "self.number.try_into()?"))]
    pub number: NonZeroU32,
    /// Mapping quality range [min, max]
    #[builder(field(ty = "(u8, u8)", build = "self.mapq_range.try_into()?"))]
    pub mapq_range: OrdPair<u8>,
    /// Base quality score range [min, max]
    #[builder(field(ty = "(u8, u8)", build = "self.base_qual_range.try_into()?"))]
    pub base_qual_range: OrdPair<u8>,
    /// Read length range as fraction of contig [min, max] (e.g.: [0.1, 0.8] = 10% to 80%)
    #[builder(field(ty = "(f32, f32)", build = "self.len_range.try_into()?"))]
    pub len_range: OrdPair<F32Bw0and1>,
    /// Optional barcode DNA sequence to add to read ends
    #[builder(field(
        ty = "String",
        build = "(!self.barcode.is_empty()).then(|| DNARestrictive::from_str(&self.barcode)).transpose()?"
    ))]
    pub barcode: Option<DNARestrictive>,
    /// Optional deletion: fractional range [start, end] of read to delete (e.g., [0.5, 0.7] deletes middle 20%)
    #[builder(field(
        ty = "(f32, f32)",
        build = "Some(self.delete).map(TryInto::try_into).transpose()?"
    ))]
    pub delete: Option<OrdPair<F32Bw0and1>>,
    /// Optional sequence to insert at the middle of the read
    #[builder(field(
        ty = "String",
        build = "(!self.insert_middle.is_empty()).then(|| DNARestrictive::from_str(&self.insert_middle)).transpose()?"
    ))]
    pub insert_middle: Option<DNARestrictive>,
    /// Optional mismatch fraction: random fraction of bases to mutate (e.g., 0.5 = 50% of bases)
    #[builder(field(ty = "f32", build = "Some(F32Bw0and1::try_from(self.mismatch)?)"))]
    pub mismatch: Option<F32Bw0and1>,
    /// Modification configurations
    pub mods: Vec<ModConfig>,
}

/// Configuration for modification generation in simulated BAM files.
/// Also refer to [`SimulationConfig`] to see how this `struct` can be used,
/// and [`ModConfigBuilder`] to see how it can be built as shown below.
///
/// # Example
///
/// Configure modification for cytosines on plus strand.
/// Here, 2Cs have probabilities randomly chosen b/w 0.4-0.8,
///       3Cs have probabilities b/w 0.5-0.7,
///       2Cs have ...,
///       3Cs have ...,
///       ...
///  repeated forever. This can be passed as an input to a routine
///  sometime later and applied on a given sequence.
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::ModConfigBuilder;
///
/// let mod_config_c = ModConfigBuilder::default()
///     .base('C')
///     .is_strand_plus(true)
///     .mod_code("m".into())
///     .win(vec![2, 3])
///     .mod_range(vec![(0.4, 0.8), (0.5, 0.7)]).build()?;
/// # Ok::<(), Error>(())
/// ```
#[derive(Builder, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[builder(default, build_fn(error = "Error"), pattern = "owned", derive(Clone))]
#[non_exhaustive]
pub struct ModConfig {
    /// Base that is modified (A, C, G, T, or N)
    #[builder(field(ty = "char", build = "self.base.try_into()?"))]
    pub base: AllowedAGCTN,
    /// Whether this is on the plus strand
    pub is_strand_plus: bool,
    /// Modification code (character or numeric)
    #[builder(field(ty = "String", build = "self.mod_code.parse()?"))]
    pub mod_code: ModChar,
    /// Vector of window sizes for modification density variation.
    /// e.g. if you want reads with a window of 100 bases with each
    /// modified with a probability in the range 0.4-0.6 and the next
    /// 200 modified in the range 0.1-0.2 (and this two window config
    /// repeating forever), you need to set this win array to
    /// [100, 200] and the mod range array to [[0.4, 0.6], [0.1, 0.2]]
    /// (Remembering to adjust the datatypes of the inputs suitably
    /// i.e. use `NonZeroU32` etc.)
    /// NOTE: "bases" in the above description refer to bases of interest
    /// set in the base field i.e. 100 bases with base set to "T" mean
    /// 100 thymidines specifically.
    #[builder(field(
        ty = "Vec<u32>",
        build = "self.win.iter().map(|&x| NonZeroU32::new(x).ok_or(Error::Zero(\"cannot use zero-\
sized windows in builder\".to_owned()))).collect::<Result<Vec<NonZeroU32>,_>>()?"
    ))]
    pub win: Vec<NonZeroU32>,
    /// Vector of modification density range e.g. [[0.4, 0.6], [0.1, 0.2]].
    /// Also see description of `win` above.
    #[builder(field(
        ty = "Vec<(f32, f32)>",
        build = "self.mod_range.iter().map(|&x| OF::try_from(x)).collect::<Result<Vec<OF>, _>>()?"
    ))]
    pub mod_range: Vec<OrdPair<F32Bw0and1>>,
}

/// Represents a contig with name and sequence.
/// Can be built using [`ContigConfigBuilder`] as shown below.
///
/// # Example
///
/// Example contig with a simple sequence and name, to be passed
/// somewhere else to be constructed.
///
/// ```
/// use nanalogue_core::{Error, simulate_mod_bam::ContigBuilder};
///
/// let contig = ContigBuilder::default()
///     .name("chr1")
///     .seq("ACGTACGTACGTACGT".into()).build()?;
/// # Ok::<(), Error>(())
#[derive(Builder, Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
#[builder(default, build_fn(error = "Error"))]
#[non_exhaustive]
pub struct Contig {
    /// Contig name
    #[builder(setter(into))]
    pub name: String,
    /// Contig sequence (A, C, G, T)
    #[builder(field(ty = "String", build = "self.seq.parse()?"))]
    pub seq: DNARestrictive,
}

impl GetDNARestrictive for Contig {
    /// Returns a reference to the contig's DNA
    fn get_dna_restrictive(&self) -> &DNARestrictive {
        &self.seq
    }
}

impl Default for Contig {
    fn default() -> Self {
        Self {
            name: String::new(),
            seq: DNARestrictive::from_str("A").expect("valid default DNA"),
        }
    }
}

impl Default for ContigConfig {
    fn default() -> Self {
        Self {
            number: NonZeroU32::new(1).unwrap(),
            len_range: OrdPair::new(NonZeroU64::new(1).unwrap(), NonZeroU64::new(1).unwrap())
                .unwrap(),
            repeated_seq: None,
        }
    }
}

impl Default for ReadConfig {
    fn default() -> Self {
        Self {
            number: NonZeroU32::new(1).unwrap(),
            mapq_range: OrdPair::new(0, 0).unwrap(),
            base_qual_range: OrdPair::new(0, 0).unwrap(),
            len_range: ord_pair_f32_bw0and1!(0.0, 0.0),
            barcode: None,
            delete: None,
            insert_middle: None,
            mismatch: None,
            mods: Vec::new(),
        }
    }
}

impl Default for ModConfig {
    fn default() -> Self {
        Self {
            base: AllowedAGCTN::C,
            is_strand_plus: true,
            mod_code: ModChar::new('m'),
            win: vec![NonZeroU32::new(1).unwrap()],
            mod_range: vec![ord_pair_f32_bw0and1!(0.0, 1.0)],
        }
    }
}

/// Builder for creating a sequence with cigar string and optional barcode
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerfectSeqMatchToNot {
    /// The DNA sequence to be processed
    seq: Vec<u8>,
    /// Optional barcode to add to both ends of the sequence
    barcode: Option<DNARestrictive>,
    /// Optional deletion: fractional range of sequence to delete
    delete: Option<OrdPair<F32Bw0and1>>,
    /// Optional sequence to insert at the middle
    insert_middle: Option<DNARestrictive>,
    /// Optional mismatch fraction
    mismatch: Option<F32Bw0and1>,
}

impl PerfectSeqMatchToNot {
    /// Creates a new builder with the given sequence
    ///
    /// # Errors
    /// Returns `Error::InvalidState` if the sequence is empty
    ///
    /// # Examples
    ///
    /// Valid sequence:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    ///
    /// let builder = PerfectSeqMatchToNot::seq(b"ACGT".to_vec()).unwrap();
    /// ```
    ///
    /// Empty sequence returns error:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::Error;
    ///
    /// let result = PerfectSeqMatchToNot::seq(b"".to_vec());
    /// assert!(matches!(result, Err(Error::InvalidState(_))));
    /// ```
    pub fn seq(seq: Vec<u8>) -> Result<Self, Error> {
        if seq.is_empty() {
            return Err(Error::InvalidState(
                "Sequence length is 0; cannot create PerfectSeqMatchToNot with empty sequence"
                    .into(),
            ));
        }
        Ok(Self {
            seq,
            barcode: None,
            delete: None,
            insert_middle: None,
            mismatch: None,
        })
    }

    /// Sets the barcode for this sequence
    #[must_use]
    pub fn barcode(mut self, barcode: DNARestrictive) -> Self {
        self.barcode = Some(barcode);
        self
    }

    /// Sets the deletion range for this sequence
    #[must_use]
    pub fn delete(mut self, delete: OrdPair<F32Bw0and1>) -> Self {
        self.delete = Some(delete);
        self
    }

    /// Sets the sequence to insert at the middle
    #[must_use]
    pub fn insert_middle(mut self, insert: DNARestrictive) -> Self {
        self.insert_middle = Some(insert);
        self
    }

    /// Sets the mismatch fraction for this sequence
    #[must_use]
    pub fn mismatch(mut self, mismatch: F32Bw0and1) -> Self {
        self.mismatch = Some(mismatch);
        self
    }

    /// Builds the final sequence with barcode (if specified) and corresponding cigar string
    ///
    /// # Examples
    ///
    /// Without barcode, forward read:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, Error};
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// assert_eq!(seq, b"GGGGGGGG");
    /// assert_eq!(cigar.expect("no error").to_string(), "8M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// Without barcode, reverse read:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, Error};
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
    ///     .build(ReadState::PrimaryRev, &mut rng)?;
    /// assert_eq!(seq, b"GGGGGGGG");
    /// assert_eq!(cigar.expect("no error").to_string(), "8M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// With barcode, forward read (barcode + seq + revcomp(barcode)):
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, DNARestrictive, Error};
    /// use std::str::FromStr;
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let barcode = DNARestrictive::from_str("ACGTAA").unwrap();
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
    ///     .barcode(barcode)
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// assert_eq!(seq, b"ACGTAAGGGGGGGGTTACGT");
    /// assert_eq!(cigar.expect("no error").to_string(), "6S8M6S");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// With barcode, reverse read (comp(barcode) + seq + rev(barcode)):
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, DNARestrictive, Error};
    /// use std::str::FromStr;
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let barcode = DNARestrictive::from_str("ACGTAA").unwrap();
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
    ///     .barcode(barcode)
    ///     .build(ReadState::PrimaryRev, &mut rng)?;
    /// assert_eq!(seq, b"TGCATTGGGGGGGGAATGCA");
    /// assert_eq!(cigar.expect("no error").to_string(), "6S8M6S");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// Unmapped read returns None for cigar:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, Error};
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
    ///     .build(ReadState::Unmapped, &mut rng)?;
    /// assert_eq!(seq, b"GGGGGGGG");
    /// assert!(cigar.is_none());
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// With deletion (removes a portion of the sequence):
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, F32Bw0and1, OrdPair, Error};
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let delete_range = OrdPair::new(
    ///     F32Bw0and1::try_from(0.5)?,
    ///     F32Bw0and1::try_from(0.75)?
    /// )?;
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAATTTTCCCCGGGG".to_vec())?
    ///     .delete(delete_range)
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// // Deletes positions 8-12 (CCCC), resulting in AAAATTTTGGGG
    /// assert_eq!(seq, b"AAAATTTTGGGG");
    /// assert_eq!(cigar.expect("no error").to_string(), "8M4D4M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// With insertion in the middle:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, DNARestrictive, Error};
    /// use std::str::FromStr;
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let insert_seq = DNARestrictive::from_str("TTTT")?;
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAGGGG".to_vec())?
    ///     .insert_middle(insert_seq)
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// // Inserts TTTT at position 4 (middle), resulting in AAAATTTTGGGG
    /// assert_eq!(seq, b"AAAATTTTGGGG");
    /// assert_eq!(cigar.expect("no error").to_string(), "4M4I4M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// With mismatches (randomly changes bases):
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, F32Bw0and1, Error};
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let mismatch_frac = F32Bw0and1::try_from(0.5)?;
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())?
    ///     .mismatch(mismatch_frac)
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// // 50% of bases (4 out of 8) will be changed to different bases
    /// let mismatch_count = seq.iter().filter(|&&b| b != b'A').count();
    /// assert_eq!(mismatch_count, 4);
    /// // CIGAR remains 8M (mismatches don't change CIGAR)
    /// assert_eq!(cigar.expect("no error").to_string(), "8M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// Combining deletion and insertion:
    /// ```
    /// use nanalogue_core::simulate_mod_bam::PerfectSeqMatchToNot;
    /// use nanalogue_core::{ReadState, F32Bw0and1, OrdPair, DNARestrictive, Error};
    /// use std::str::FromStr;
    /// use rand::Rng;
    ///
    /// let mut rng = rand::rng();
    /// let delete_range = OrdPair::new(
    ///     F32Bw0and1::try_from(0.5)?,
    ///     F32Bw0and1::try_from(0.75)?
    /// )?;
    /// let insert_seq = DNARestrictive::from_str("TT")?;
    /// let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAACCCCGGGG".to_vec())?
    ///     .delete(delete_range)
    ///     .insert_middle(insert_seq)
    ///     .build(ReadState::PrimaryFwd, &mut rng)?;
    /// // Applies both deletion and insertion operations
    /// assert_eq!(seq, b"AAAACCTTGGG");
    /// assert_eq!(cigar.expect("no error").to_string(), "6M2I3D3M");
    /// # Ok::<(), Error>(())
    /// ```
    ///
    /// # Returns
    /// A tuple of (`final_sequence`, `cigar_string`) wrapped in a `Result` where:
    /// - `final_sequence` includes barcodes if specified
    /// - `cigar_string` includes `SoftClip` operations for barcodes, or `None` if unmapped
    ///
    /// # Errors
    /// - If parameters result in a sequence with no mapped bases i.e. a sequence without
    ///   any M characters in the CIGAR string.
    /// - If a deletion occurs right after a softclip at the start of a sequence
    ///   a cigar like "20S10D..." is not valid as we can just shift the start of the sequence
    ///   and make the cigar "20S...". We will end up in this state if the deletion is right at
    ///   the beginning of the sequence. We may deal with this in the future by shifting the start
    ///   of the sequence, but we don't want to do this right now. A similar problem arises if
    ///   the deletion is at the end of a sequence.
    ///
    /// # Panics
    /// Panics on number conversion errors (sequence or barcode length overflow)
    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "Casting and arithmetic needed for fractional calculations on sequence positions"
    )]
    #[expect(
        clippy::too_many_lines,
        reason = "performs many steps to alter sequence (indel, mismatch, barcode)"
    )]
    pub fn build<R: Rng>(
        self,
        read_state: ReadState,
        rng: &mut R,
    ) -> Result<(Vec<u8>, Option<CigarString>), Error> {
        let seq = self.seq;

        // Step 1: Create initial representation as (base, operation) tuples
        // All bases start with 'M' for Match operation
        let mut bases_and_ops: Vec<(u8, u8)> = seq.iter().map(|&base| (base, b'M')).collect();

        // Step 2: Apply mismatch (randomly mutate bases, keep 'M' operation)
        // We use `choose_multiple` on indices to preserve position information,
        // unlike `partial_shuffle` which would reorder elements and destroy positions.
        if let Some(mismatch_frac) = self.mismatch {
            let num_mismatches =
                ((bases_and_ops.len() as f32) * mismatch_frac.val()).round() as usize;

            let indices_to_mutate: Vec<usize> =
                (0..bases_and_ops.len()).choose_multiple(rng, num_mismatches);

            for idx in indices_to_mutate {
                let item = bases_and_ops
                    .get_mut(idx)
                    .expect("idx is within bounds from choose_multiple");
                let current_base = item.0;
                let new_base = match current_base {
                    v @ (b'A' | b'C' | b'G' | b'T') => {
                        // Sample random bases until we get A/C/G/T different from the current
                        loop {
                            let candidate: AllowedAGCTN = rng.random();
                            let candidate_u8: u8 = candidate.into();
                            if candidate_u8 != v && candidate_u8 != b'N' {
                                break candidate_u8;
                            }
                        }
                    }
                    other => other, // Keep N and other bases as is
                };
                item.0 = new_base;
            }
        }

        // Step 3: Apply delete (mark bases as deleted with 'D' operation)
        if let Some(delete_range) = self.delete {
            let start = ((bases_and_ops.len() as f32) * delete_range.low().val()).round() as usize;
            let end_raw =
                ((bases_and_ops.len() as f32) * delete_range.high().val()).round() as usize;
            let end = end_raw.min(bases_and_ops.len());

            if let Some(slice) = bases_and_ops.get_mut(start..end) {
                for item in slice {
                    item.1 = b'D';
                }
            }
        }

        // Step 4: Apply insert_middle (add new tuples with 'I' operation)
        if let Some(insert_seq) = self.insert_middle {
            let middle = bases_and_ops.len() / 2;
            let insert_bases = insert_seq.get_dna_restrictive().get();
            let insertions: Vec<(u8, u8)> = insert_bases.iter().map(|&b| (b, b'I')).collect();

            drop(
                bases_and_ops
                    .splice(middle..middle, insertions)
                    .collect::<Vec<_>>(),
            );
        }

        // Step 5: Apply barcode (add tuples with 'S' for SoftClip operation)
        if let Some(barcode) = self.barcode {
            // Use add_barcode with empty sequence to get the transformed barcodes
            let barcoded_seq = add_barcode(&[], barcode.clone(), read_state);
            let barcode_len = barcode.get_dna_restrictive().get().len();

            // Split the result into start and end barcodes
            let (start_bc, end_bc) = barcoded_seq.split_at(barcode_len);

            // Prepend start barcode with 'S' operations
            let bc_tuples_start: Vec<(u8, u8)> = start_bc.iter().map(|&b| (b, b'S')).collect();
            drop(
                bases_and_ops
                    .splice(0..0, bc_tuples_start)
                    .collect::<Vec<_>>(),
            );

            // Append end barcode with 'S' operations
            let bc_tuples_end: Vec<(u8, u8)> = end_bc.iter().map(|&b| (b, b'S')).collect();
            bases_and_ops.extend(bc_tuples_end);
        }

        // Step 6: Build CIGAR string from operations (second entries)
        let cigar_string = CigarString(
            bases_and_ops
                .iter()
                .map(|&(_, op)| op)
                .fold(Vec::<(u8, u32)>::new(), |mut acc, op| {
                    match acc.last_mut() {
                        Some(&mut (last_op, ref mut count)) if last_op == op => {
                            *count = count.saturating_add(1);
                        }
                        _ => acc.push((op, 1u32)),
                    }
                    acc
                })
                .into_iter()
                .map(|(op, count)| match op {
                    b'M' => Cigar::Match(count),
                    b'I' => Cigar::Ins(count),
                    b'D' => Cigar::Del(count),
                    b'S' => Cigar::SoftClip(count),
                    _ => unreachable!("Invalid CIGAR operation: {op}"),
                })
                .collect::<Vec<_>>(),
        );

        // Step 7: Build final sequence by filtering out deletions and collecting bases
        let final_seq: Vec<u8> = bases_and_ops
            .iter()
            .copied()
            .filter_map(|item| (item.1 != b'D').then_some(item.0))
            .collect();

        // Step 8: final checks
        let first_ok = (cigar_string.0.as_slice().first().map(|x| x.char()) == Some('M'))
            || (cigar_string
                .0
                .as_slice()
                .first_chunk::<2>()
                .map(|&x| [x[0].char(), x[1].char()])
                == Some(['S', 'M']));
        let last_ok = (cigar_string.0.as_slice().last().map(|x| x.char()) == Some('M'))
            || (cigar_string
                .0
                .as_slice()
                .last_chunk::<2>()
                .map(|&x| [x[0].char(), x[1].char()])
                == Some(['M', 'S']));
        if first_ok && last_ok {
            Ok((
                final_seq,
                (!read_state.is_unmapped()).then_some(cigar_string),
            ))
        } else {
            Err(Error::SimulateDNASeqCIGAREndProblem(
                "too few bp or insertion/deletion close to end".to_owned(),
            ))
        }
    }
}

/// Generates BAM MM and ML tags with DNA modification probabilities
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use nanalogue_core::{DNARestrictive, Error};
/// use nanalogue_core::simulate_mod_bam::{ModConfigBuilder, generate_random_dna_modification};
/// use rand::Rng;
///
/// // Create a DNA sequence with multiple cytosines
/// let seq = DNARestrictive::from_str("ACGTCGCGATCGACGTCGCGATCG").unwrap();
///
/// // Configure modification for cytosines on plus strand.
/// // NOTE: we use mod ranges with an identical low and high value below
/// // because we do not want to deal with random values in an example.
///
/// let mod_config_c = ModConfigBuilder::default()
///     .base('C')
///     .is_strand_plus(true)
///     .mod_code("m".into())
///     .win(vec![2, 3])
///     .mod_range(vec![(0.8, 0.8), (0.4, 0.4)]).build()?;
///
/// // Put modifications for A on the minus strand.
/// // Again, we use equal low and high value of 0.2 as we do not
/// // want to deal with values drawn randomly from a range.
///
/// let mod_config_a = ModConfigBuilder::default()
///     .base('A')
///     .is_strand_plus(false)
///     .mod_code("20000".into())
///     .win([2].into())
///     .mod_range(vec![(0.2, 0.2)]).build()?;
///
/// let mod_config = vec![mod_config_c, mod_config_a];
///
/// let mut rng = rand::rng();
/// let (mm_str, ml_str) = generate_random_dna_modification(&mod_config, &seq, &mut rng);
///
/// // MM string format: C+m?gap1,gap2,gap3,gap4,...;A-20000?,...;
/// assert_eq!(mm_str, String::from("C+m?,0,0,0,0,0,0,0,0;A-20000?,0,0,0,0;"));
///
/// // ML string contains probabilities
/// assert_eq!(ml_str, vec![204, 204, 102, 102, 102, 204, 204, 102, 51, 51, 51, 51]);
/// # Ok::<(), Error>(())
/// ```
///
pub fn generate_random_dna_modification<R: Rng, S: GetDNARestrictive>(
    mod_configs: &[ModConfig],
    seq: &S,
    rng: &mut R,
) -> (String, Vec<u8>) {
    let seq_bytes = seq.get_dna_restrictive().get();
    let mut mm_str = String::new();

    // rough estimate of capacity below
    let mut ml_vec: Vec<u8> = Vec::with_capacity(seq_bytes.len());

    for mod_config in mod_configs {
        let base = u8::from(mod_config.base);
        let strand = if mod_config.is_strand_plus { '+' } else { '-' };
        let mod_code = mod_config.mod_code;
        let mut count = if base == b'N' {
            seq_bytes.len()
        } else {
            seq_bytes
                .iter()
                .zip(iter::repeat(&base))
                .filter(|&(&a, &b)| a == b)
                .count()
        };
        let mut output: Vec<u8> = Vec::with_capacity(count);
        for k in mod_config
            .win
            .iter()
            .cycle()
            .zip(mod_config.mod_range.iter().cycle())
        {
            let low = u8::from(k.1.low());
            let high = u8::from(k.1.high());
            #[expect(
                clippy::redundant_else,
                reason = "so that the clippy arithmetic lint fits better with the code"
            )]
            #[expect(
                clippy::arithmetic_side_effects,
                reason = "we loop only if count > 0 and catch count == 0, thus count doesn't underflow"
            )]
            if count == 0 {
                break;
            } else {
                for _ in 0..k.0.get() {
                    output.push(rng.random_range(low..=high));
                    count -= 1;
                    if count == 0 {
                        break;
                    }
                }
            }
        }
        if !output.is_empty() {
            let mod_len = output.len();
            ml_vec.append(&mut output);
            mm_str += format!(
                "{}{}{}?,{};",
                base as char,
                strand,
                mod_code,
                join(vec![0; mod_len], ",")
            )
            .as_str();
        }
    }
    ml_vec.shrink_to_fit();
    (mm_str, ml_vec)
}

/// Generates random DNA sequence of given length
///
/// # Panics
/// Panics if the sequence length exceeds `usize::MAX` (2^32 - 1 on 32-bit systems, 2^64 - 1 on 64-bit systems).
///
/// ```
/// use std::num::NonZeroU64;
/// use rand::Rng;
/// use nanalogue_core::simulate_mod_bam::generate_random_dna_sequence;
///
/// let mut rng = rand::rng();
/// let seq = generate_random_dna_sequence(100.try_into().expect("no error"), &mut rng);
/// assert_eq!(seq.len(), 100);
/// assert!(seq.iter().all(|&base| [b'A', b'C', b'G', b'T'].contains(&base)));
/// ```
pub fn generate_random_dna_sequence<R: Rng>(length: NonZeroU64, rng: &mut R) -> Vec<u8> {
    const DNA_BASES: [u8; 4] = [b'A', b'C', b'G', b'T'];
    iter::repeat_with(|| {
        *DNA_BASES
            .get(rng.random_range(0..4))
            .expect("random_range(0..4) is always 0-3")
    })
    .take(usize::try_from(length.get()).expect("sequence length exceeds usize::MAX"))
    .collect()
}

/// Adds barcodes to read sequence based on strand orientation.
///
/// For forward and unmapped reads:
/// - Prepends barcode to read sequence
/// - Appends reverse complement of barcode to read sequence
///
/// For reverse reads:
/// - Prepends complement of barcode to read sequence
/// - Appends reverse of barcode (not reverse complement) to read sequence
///
/// # Examples
/// ```
/// use nanalogue_core::simulate_mod_bam::add_barcode;
/// use nanalogue_core::{ReadState, DNARestrictive};
/// use std::str::FromStr;
///
/// // Forward read: barcode + seq + revcomp(barcode)
/// let result = add_barcode("GGGGGGGG".as_bytes(), "ACGTAA".parse().unwrap(), ReadState::PrimaryFwd);
/// assert_eq!(result, b"ACGTAAGGGGGGGGTTACGT".to_vec());
///
/// // Reverse read: comp(barcode) + seq + rev(barcode)
/// let result = add_barcode("GGGGGGGG".as_bytes(), "ACGTAA".parse().unwrap(), ReadState::PrimaryRev);
/// assert_eq!(result, b"TGCATTGGGGGGGGAATGCA".to_vec());
/// ```
#[must_use]
#[expect(
    clippy::needless_pass_by_value,
    reason = "barcode by value allows passing `&'static str` easily (I think, may fix in future). \
If you don't know what this means, ignore this; this is _not_ a bug."
)]
pub fn add_barcode(read_seq: &[u8], barcode: DNARestrictive, read_state: ReadState) -> Vec<u8> {
    let bc_bytes = barcode.get();

    match read_state {
        ReadState::PrimaryFwd
        | ReadState::SecondaryFwd
        | ReadState::SupplementaryFwd
        | ReadState::Unmapped => {
            // Forward/Unmapped: barcode + read_seq + reverse_complement(barcode)
            let revcomp_bc = bio::alphabets::dna::revcomp(bc_bytes);
            [bc_bytes, read_seq, &revcomp_bc[..]].concat()
        }
        ReadState::PrimaryRev | ReadState::SecondaryRev | ReadState::SupplementaryRev => {
            // Reverse: complement(barcode) + read_seq + reverse(barcode)
            let comp_bc: Vec<u8> = bc_bytes
                .iter()
                .map(|&b| bio::alphabets::dna::complement(b))
                .collect();
            let rev_bc: Vec<u8> = bc_bytes.iter().copied().rev().collect();
            [&comp_bc[..], read_seq, &rev_bc[..]].concat()
        }
    }
}

/// Generates contigs with random sequence according to configuration
///
/// ```
/// use std::num::{NonZeroU32, NonZeroU64};
/// use nanalogue_core::{OrdPair, GetDNARestrictive};
/// use nanalogue_core::simulate_mod_bam::generate_contigs_denovo;
/// use rand::Rng;
///
/// let mut rng = rand::rng();
/// let contigs = generate_contigs_denovo(
///     3.try_into().unwrap(),
///     (100, 200).try_into().unwrap(),
///     &mut rng
/// );
/// assert_eq!(contigs.len(), 3);
/// assert!(contigs.iter().all(|c| (100..=200).contains(&c.get_dna_restrictive().get().len())));
/// ```
///
#[expect(
    clippy::missing_panics_doc,
    reason = "no length number or DNA conversion problems expected"
)]
pub fn generate_contigs_denovo<R: Rng>(
    contig_number: NonZeroU32,
    len_range: OrdPair<NonZeroU64>,
    rng: &mut R,
) -> Vec<Contig> {
    (0..contig_number.get())
        .map(|i| {
            let length = rng.random_range(len_range.low().get()..=len_range.high().get());
            let seq_bytes =
                generate_random_dna_sequence(NonZeroU64::try_from(length).expect("no error"), rng);
            let seq_str = String::from_utf8(seq_bytes).expect("valid DNA sequence");
            ContigBuilder::default()
                .name(format!("contig_{i:05}"))
                .seq(seq_str)
                .build()
                .expect("no error")
        })
        .collect()
}

/// Generates contigs with repeated sequence pattern
///
/// Creates contigs by repeating a given DNA sequence to reach a random length
/// within the specified range. The last repetition is clipped if needed.
///
/// ```
/// use std::num::{NonZeroU32, NonZeroU64};
/// use std::str::FromStr;
/// use nanalogue_core::{DNARestrictive, GetDNARestrictive, OrdPair};
/// use nanalogue_core::simulate_mod_bam::generate_contigs_denovo_repeated_seq;
/// use rand::Rng;
///
/// let mut rng = rand::rng();
/// let seq = DNARestrictive::from_str("ACGT").unwrap();
/// let contigs = generate_contigs_denovo_repeated_seq(
///     2.try_into().unwrap(),
///     (10, 12).try_into().unwrap(),
///     &seq,
///     &mut rng
/// );
/// assert_eq!(contigs.len(), 2);
/// for (i, contig) in contigs.iter().enumerate() {
///     assert_eq!(contig.name, format!("contig_0000{i}"));
///     match contig.get_dna_restrictive().get() {
///         b"ACGTACGTAC" | b"ACGTACGTACG" | b"ACGTACGTACGT" => {},
///         _ => panic!("Unexpected sequence"),
///     }
/// }
/// ```
#[expect(
    clippy::missing_panics_doc,
    reason = "no length number or DNA conversion problems expected"
)]
pub fn generate_contigs_denovo_repeated_seq<R: Rng, S: GetDNARestrictive>(
    contig_number: NonZeroU32,
    len_range: OrdPair<NonZeroU64>,
    seq: &S,
    rng: &mut R,
) -> Vec<Contig> {
    (0..contig_number.get())
        .map(|i| {
            let length = rng.random_range(len_range.low().get()..=len_range.high().get());
            let contig_seq: Vec<u8> = seq
                .get_dna_restrictive()
                .get()
                .iter()
                .cycle()
                .take(usize::try_from(length).expect("number conversion error"))
                .copied()
                .collect();
            let seq_str =
                String::from_utf8(contig_seq).expect("valid UTF-8 from repeated DNA sequence");
            ContigBuilder::default()
                .name(format!("contig_{i:05}"))
                .seq(seq_str)
                .build()
                .expect("valid DNA sequence from repeated pattern")
        })
        .collect()
}

/// Generates reads that align to contigs
///
/// # Example
///
/// Here we generate a contig, specify read properties, and ask for them to be generated.
/// Although we have used `ContigBuilder` here, you can also use `DNARestrictive` to pass
/// DNA sequences directly in the first argument i.e. you can use any `struct` that implements
/// `GetDNARestrictive`.
///
/// ```
/// use nanalogue_core::Error;
/// use nanalogue_core::simulate_mod_bam::{ContigBuilder, ReadConfigBuilder, generate_reads_denovo};
/// use rand::Rng;
///
/// let mut contig = ContigBuilder::default()
///     .name("chr1")
///     .seq("ACGTACGTACGTACGT".into()).build()?;
/// let contigs = vec![contig];
///
/// let mut config = ReadConfigBuilder::default()
///     .number(10)
///     .mapq_range((10, 20))
///     .base_qual_range((20, 30))
///     .len_range((0.2, 0.5)).build()?;
/// // NOTE: barcodes are optional, and will add 2*barcode_length to length statistics.
/// //       i.e. length stats are imposed independent of barcodes.
/// let mut rng = rand::rng();
/// let reads = generate_reads_denovo(&contigs, &config, "RG1", &mut rng).unwrap();
/// assert_eq!(reads.len(), 10);
/// # Ok::<(), Error>(())
/// ```
///
/// # Errors
/// Returns an error if the contigs input slice is empty,
/// if parameters are such that zero read lengths are produced,
/// or if BAM record creation fails, such as when making RG, MM, or ML tags.
#[expect(
    clippy::missing_panics_doc,
    clippy::too_many_lines,
    reason = "number conversion errors or mis-generation of DNA bases are unlikely \
    as we generate DNA sequences ourselves here, and genomic data are unlikely \
    to exceed ~2^63 bp or have ~2^32 contigs. Function length is acceptable for read generation"
)]
#[expect(
    clippy::cast_possible_truncation,
    reason = "read length calculated as a fraction of contig length, managed with trunc()"
)]
pub fn generate_reads_denovo<R: Rng, S: GetDNARestrictive>(
    contigs: &[S],
    read_config: &ReadConfig,
    read_group: &str,
    rng: &mut R,
) -> Result<Vec<bam::Record>, Error> {
    if contigs.is_empty() {
        return Err(Error::UnavailableData("no contigs found".to_owned()));
    }

    let mut reads = Vec::new();

    for _ in 0..read_config.number.get() {
        // Select a random contig
        let contig_idx = rng.random_range(0..contigs.len());
        let contig = contigs
            .get(contig_idx)
            .expect("contig_idx is within contigs range");
        let contig_len = contig.get_dna_restrictive().get().len() as u64;

        // Calculate read length as fraction of contig length
        #[expect(
            clippy::cast_precision_loss,
            reason = "u64->f32 causes precision loss but we are fine with this for now"
        )]
        #[expect(
            clippy::cast_sign_loss,
            reason = "these are positive numbers so no problem"
        )]
        let read_len = ((rng
            .random_range(read_config.len_range.low().val()..=read_config.len_range.high().val())
            * contig_len as f32)
            .trunc() as u64)
            .min(contig_len);

        // Set starting position
        let start_pos = rng.random_range(0..=(contig_len.saturating_sub(read_len)));

        // Extract sequence from contig
        let random_state: ReadState = rng.random();
        let end_pos = usize::try_from(start_pos.checked_add(read_len).expect("u64 overflow"))
            .expect("number conversion error");
        let (read_seq, cigar) = {
            let start_idx = usize::try_from(start_pos).expect("number conversion error");
            let temp_seq = contig
                .get_dna_restrictive()
                .get()
                .get(start_idx..end_pos)
                .expect("start_idx and end_pos are within contig bounds")
                .to_vec();
            let mut builder = PerfectSeqMatchToNot::seq(temp_seq)?;
            if let Some(barcode) = read_config.barcode.clone() {
                builder = builder.barcode(barcode);
            }
            if let Some(delete) = read_config.delete {
                builder = builder.delete(delete);
            }
            if let Some(insert_middle) = read_config.insert_middle.clone() {
                builder = builder.insert_middle(insert_middle);
            }
            if let Some(mismatch) = read_config.mismatch {
                builder = builder.mismatch(mismatch);
            }
            builder.build(random_state, rng)?
        };

        // Generate quality scores (for final read length including any adjustments like barcodes)
        let qual: Vec<u8> = iter::repeat_with(|| {
            rng.random_range(RangeInclusive::from(read_config.base_qual_range))
        })
        .take(read_seq.len())
        .collect();

        // Generate modification information after reverse complementing sequence if needed
        let seq: DNARestrictive;
        let (mod_prob_mm_tag, mod_pos_ml_tag) = generate_random_dna_modification(
            &read_config.mods,
            match random_state.strand() {
                '.' | '+' => {
                    seq = DNARestrictive::from_str(str::from_utf8(&read_seq).expect("no error"))
                        .expect("no error");
                    &seq
                }
                '-' => {
                    seq = DNARestrictive::from_str(
                        str::from_utf8(&bio::alphabets::dna::revcomp(&read_seq)).expect("no error"),
                    )
                    .expect("no error");
                    &seq
                }
                _ => unreachable!("`strand` is supposed to return one of +/-/."),
            },
            rng,
        );

        // Create BAM record
        let record = {
            let mut record = bam::Record::new();
            let uuid = {
                let mut bytes = [0u8; 16];
                rng.fill(&mut bytes);
                uuid::Builder::from_random_bytes(bytes).into_uuid()
            };
            let qname = format!("{read_group}.{uuid}").into_bytes();
            record.unset_flags();
            record.set_flags(u16::from(random_state));
            if random_state == ReadState::Unmapped {
                record.set(&qname, None, &read_seq, &qual);
                record.set_mapq(255);
                record.set_tid(-1);
                record.set_pos(-1);
            } else {
                let mapq = rng.random_range(RangeInclusive::from(read_config.mapq_range));
                record.set(&qname, cigar.as_ref(), &read_seq, &qual);
                record.set_mapq(mapq);
                record.set_tid(i32::try_from(contig_idx).expect("number conversion error"));
                record.set_pos(i64::try_from(start_pos).expect("number conversion error"));
            }
            record.set_mpos(-1);
            record.set_mtid(-1);
            record.push_aux(b"RG", Aux::String(read_group))?;
            if !mod_prob_mm_tag.is_empty() && !mod_pos_ml_tag.is_empty() {
                record.push_aux(b"MM", Aux::String(mod_prob_mm_tag.as_str()))?;
                record.push_aux(b"ML", Aux::ArrayU8((&mod_pos_ml_tag).into()))?;
            }
            record
        };
        reads.push(record);
    }

    Ok(reads)
}

/// Main function to generate simulated BAM file
///
/// # Example
///
/// ```
/// use nanalogue_core::{Error, SimulationConfig, simulate_mod_bam::run};
/// use uuid::Uuid;
///
/// let config_json = r#"{
///   "contigs": {
///     "number": 4,
///     "len_range": [1000, 8000]
///   },
///   "reads": [{
///     "number": 1000,
///     "mapq_range": [10, 20],
///     "base_qual_range": [10, 20],
///     "len_range": [0.1, 0.8]
///   }]
/// }"#;
///
/// // Note: * Optional "barcode" field can be added to reads (e.g., "barcode": "ACGTAA")
/// //         Length statistics are imposed independent of barcodes; so they will add
/// //         2x barcode length on top of these.
/// //       * Optional "repeated_seq" field can be added to contigs (e.g., "repeated_seq": "ACGT")
/// //         to create contigs by repeating a sequence instead of random generation.
/// //       * Optional modifications can be added using the "mods" field
/// //       * Optional "seed" field can be added (e.g., "seed": 12345) for reproducible output
/// // Note: The files used below should not exist because they will be created by this function.
/// //       If they exist, they will be overwritten.
///
/// let config: SimulationConfig = serde_json::from_str(&config_json)?;
/// let temp_dir = std::env::temp_dir();
/// let bam_path = temp_dir.join(format!("{}.bam", Uuid::new_v4()));
/// let fasta_path = temp_dir.join(format!("{}.fa", Uuid::new_v4()));
/// let bai_path = bam_path.with_extension("bam.bai");
/// run(config, &bam_path, &fasta_path)?;
/// std::fs::remove_file(&bam_path)?;
/// std::fs::remove_file(&fasta_path)?;
/// std::fs::remove_file(&bai_path)?;
/// # Ok::<(), Error>(())
/// ```
///
/// # Errors
/// Returns an error if JSON parsing fails, read generation fails, or BAM/FASTA writing fails.
pub fn run<F>(
    config: SimulationConfig,
    bam_output_path: &F,
    fasta_output_path: &F,
) -> Result<(), Error>
where
    F: AsRef<Path> + ?Sized,
{
    if let Some(s) = config.seed {
        let mut rng = StdRng::seed_from_u64(s);
        run_inner(config, bam_output_path, fasta_output_path, &mut rng)
    } else {
        let mut rng = rand::rng();
        run_inner(config, bam_output_path, fasta_output_path, &mut rng)
    }
}

/// Generates simulated BAM and FASTA files using the provided RNG.
fn run_inner<F, R: Rng>(
    config: SimulationConfig,
    bam_output_path: &F,
    fasta_output_path: &F,
    rng: &mut R,
) -> Result<(), Error>
where
    F: AsRef<Path> + ?Sized,
{
    let contigs = match config.contigs.repeated_seq {
        Some(seq) => generate_contigs_denovo_repeated_seq(
            config.contigs.number,
            config.contigs.len_range,
            &seq,
            rng,
        ),
        None => generate_contigs_denovo(config.contigs.number, config.contigs.len_range, rng),
    };
    let read_groups: Vec<String> = (0..config.reads.len()).map(|k| k.to_string()).collect();
    let reads = {
        let mut temp_reads = Vec::new();
        for k in config.reads.into_iter().zip(read_groups.clone()) {
            temp_reads.append(&mut generate_reads_denovo(&contigs, &k.0, &k.1, rng)?);
        }
        temp_reads.sort_by_key(|k| (k.is_unmapped(), k.tid(), k.pos(), k.is_reverse()));
        temp_reads
    };

    write_bam_denovo(
        reads,
        contigs
            .iter()
            .map(|k| (k.name.clone(), k.get_dna_restrictive().get().len())),
        read_groups,
        vec![String::from("simulated BAM file, not real data")],
        bam_output_path,
    )?;
    write_fasta(
        contigs.into_iter().map(|k| (k.name.clone(), k)),
        fasta_output_path,
    )?;

    Ok(())
}

/// Temporary BAM simulation with automatic cleanup
///
/// Creates temporary BAM and FASTA files for testing purposes and
/// automatically removes them when dropped.
#[derive(Debug, Serialize, Deserialize)]
pub struct TempBamSimulation {
    /// Path to bam file that will be created
    bam_path: String,
    /// Path to fasta file that will be created
    fasta_path: String,
}

impl TempBamSimulation {
    /// Creates a new temporary BAM simulation from JSON configuration
    ///
    /// # Errors
    /// Returns an error if the simulation run fails
    pub fn new(config: SimulationConfig) -> Result<Self, Error> {
        let temp_dir = std::env::temp_dir();
        let bam_path = temp_dir.join(format!("{}.bam", Uuid::new_v4()));
        let fasta_path = temp_dir.join(format!("{}.fa", Uuid::new_v4()));

        run(config, &bam_path, &fasta_path)?;

        Ok(Self {
            bam_path: bam_path.to_string_lossy().to_string(),
            fasta_path: fasta_path.to_string_lossy().to_string(),
        })
    }

    /// Returns the path to the temporary BAM file
    #[must_use]
    pub fn bam_path(&self) -> &str {
        &self.bam_path
    }

    /// Returns the path to the temporary FASTA file
    #[must_use]
    pub fn fasta_path(&self) -> &str {
        &self.fasta_path
    }
}

impl Drop for TempBamSimulation {
    fn drop(&mut self) {
        // Ignore errors during cleanup - files may already be deleted
        drop(std::fs::remove_file(&self.bam_path));
        drop(std::fs::remove_file(&self.fasta_path));
        drop(std::fs::remove_file(&(self.bam_path.clone() + ".bai")));
    }
}

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

    /// Test for generation of random DNA of a given length
    #[test]
    fn generate_random_dna_sequence_works() {
        let seq = generate_random_dna_sequence(NonZeroU64::new(100).unwrap(), &mut rand::rng());
        assert_eq!(seq.len(), 100);
        for base in seq {
            assert!([b'A', b'C', b'G', b'T'].contains(&base));
        }
    }
}

#[cfg(test)]
mod seeded_simulation_tests {
    use super::*;
    use rust_htslib::bam::Read as _;

    fn run_seeded_simulation(config_json: &str) -> Result<Vec<bam::Record>, Error> {
        let config: SimulationConfig = serde_json::from_str(config_json)?;
        let temp = TempBamSimulation::new(config)?;
        let mut reader = crate::nanalogue_bam_reader(temp.bam_path())?;
        reader
            .records()
            .collect::<Result<Vec<_>, _>>()
            .map_err(Error::from)
    }

    #[test]
    fn seeded_simulation_is_reproducible() -> Result<(), Error> {
        let config_json = r#"{
          "contigs": { "number": 2, "len_range": [500, 1000],
                       "repeated_seq": "ATCGAATT" },
          "reads": [{ "number": 50, "mapq_range": [10, 20],
                      "base_qual_range": [10, 20], "len_range": [0.2, 0.5],
                      "mods": [
                        { "base": "T", "is_strand_plus": true, "mod_code": "T",
                          "win": [4, 5], "mod_range": [[0.1, 0.2], [0.3, 0.4]] },
                        { "base": "C", "is_strand_plus": true, "mod_code": "m",
                          "win": [3], "mod_range": [[0.6, 0.9]] }
                      ] }],
          "seed": 12345
        }"#;

        let run_a = run_seeded_simulation(config_json)?;
        let run_b = run_seeded_simulation(config_json)?;
        assert_eq!(run_a, run_b, "same seed must produce identical BAM records");

        Ok(())
    }
}

#[cfg(test)]
mod read_generation_no_mods_tests {
    use super::*;
    use rust_htslib::bam::Read as _;

    /// Tests read generation with desired properties but no modifications
    #[test]
    fn generate_reads_denovo_no_mods_works() {
        let mut rng = rand::rng();
        let contigs = vec![
            ContigBuilder::default()
                .name("contig_0")
                .seq("ACGTACGTACGTACGTACGT".into())
                .build()
                .unwrap(),
            ContigBuilder::default()
                .name("contig_1")
                .seq("TGCATGCATGCATGCATGCA".into())
                .build()
                .unwrap(),
        ];

        let config = ReadConfigBuilder::default()
            .number(10)
            .mapq_range((10, 20))
            .base_qual_range((30, 50))
            .len_range((0.2, 0.8))
            .build()
            .unwrap();

        let reads = generate_reads_denovo(&contigs, &config, "ph", &mut rng).unwrap();
        assert_eq!(reads.len(), 10);

        for read in &reads {
            // check mapping information
            if !read.is_unmapped() {
                assert!((10..=20).contains(&read.mapq()));
                assert!((0..2).contains(&read.tid()));
            }

            // check sequence length, quality, and check that no mods are present
            assert!((4..=16).contains(&read.seq_len()));
            assert!(read.qual().iter().all(|x| (30..=50).contains(x)));
            let _: rust_htslib::errors::Error = read.aux(b"MM").unwrap_err();
            let _: rust_htslib::errors::Error = read.aux(b"ML").unwrap_err();

            // check read name, must be "ph.UUID"
            assert_eq!(read.qname().get(0..3).unwrap(), *b"ph.");
            let _: Uuid =
                Uuid::parse_str(str::from_utf8(read.qname().get(3..).unwrap()).unwrap()).unwrap();
        }
    }

    /// Tests full BAM creation
    #[test]
    fn full_bam_generation() {
        let config_json = r#"{
            "contigs": {
                "number": 2,
                "len_range": [100, 200]
            },
            "reads": [{
                "number": 1000,
                "mapq_range": [10, 20],
                "base_qual_range": [10, 20],
                "len_range": [0.1, 0.8]
            }]
        }"#;

        // create files with random names and check for existence
        let temp_dir = std::env::temp_dir();
        let bam_path = temp_dir.join(format!("{}.bam", Uuid::new_v4()));
        let fasta_path = temp_dir.join(format!("{}.fa", Uuid::new_v4()));

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        run(config, &bam_path, &fasta_path).unwrap();

        assert!(bam_path.exists());
        assert!(fasta_path.exists());

        // read BAM file and check contig, read count
        let mut reader = bam::Reader::from_path(&bam_path).unwrap();
        let header = reader.header();
        assert_eq!(header.target_count(), 2);
        assert_eq!(reader.records().count(), 1000);

        // delete files
        let bai_path = bam_path.with_extension("bam.bai");
        std::fs::remove_file(&bam_path).unwrap();
        std::fs::remove_file(fasta_path).unwrap();
        std::fs::remove_file(bai_path).unwrap();
    }

    /// Tests `TempBamSimulation` struct functionality without mods
    #[test]
    fn temp_bam_simulation_struct_no_mods() {
        let config_json = r#"{
            "contigs": {
                "number": 2,
                "len_range": [100, 200]
            },
            "reads": [{
                "number": 1000,
                "mapq_range": [10, 20],
                "base_qual_range": [10, 20],
                "len_range": [0.1, 0.8]
            }]
        }"#;

        // Create temporary simulation
        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();

        // Verify files exist
        assert!(Path::new(sim.bam_path()).exists());
        assert!(Path::new(sim.fasta_path()).exists());

        // Read BAM file and check contig count
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();
        let header = reader.header();
        assert_eq!(header.target_count(), 2);
        assert_eq!(reader.records().count(), 1000);
    }

    /// Tests `TempBamSimulation` automatic cleanup
    #[test]
    fn temp_bam_simulation_cleanup() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [50, 50]
            },
            "reads": [{
                "number": 10,
                "len_range": [0.5, 0.5]
            }]
        }"#;

        let bam_path: String;
        let fasta_path: String;

        {
            let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
            let sim = TempBamSimulation::new(config).unwrap();
            bam_path = sim.bam_path().to_string();
            fasta_path = sim.fasta_path().to_string();

            // Files should exist while sim is in scope
            assert!(Path::new(&bam_path).exists());
            assert!(Path::new(&fasta_path).exists());
        } // sim is dropped here

        // Files should be cleaned up after drop
        assert!(!Path::new(&bam_path).exists());
        assert!(!Path::new(&fasta_path).exists());
    }

    /// Tests error when generating reads with empty contigs slice
    #[test]
    fn generate_reads_denovo_empty_contigs_error() {
        let contigs: Vec<Contig> = vec![];
        let config = ReadConfig::default();
        let mut rng = rand::rng();

        let result = generate_reads_denovo(&contigs, &config, "test", &mut rng);
        assert!(matches!(result, Err(Error::UnavailableData(_))));
    }

    /// Tests error when read length would be zero
    #[test]
    fn generate_reads_denovo_zero_length_error() {
        let contigs = [ContigBuilder::default()
            .name("tiny")
            .seq("ACGT".into())
            .build()
            .unwrap()];

        let config = ReadConfigBuilder::default()
            .number(1)
            .len_range((0.0, 0.0))
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let result = generate_reads_denovo(&contigs, &config, "test", &mut rng);
        assert!(matches!(result, Err(Error::InvalidState(_))));
    }

    /// Tests invalid JSON structure causing empty reads generation
    #[test]
    fn run_empty_reads_error() {
        let invalid_json = r#"{ "reads": [] }"#; // Empty reads array
        let temp_dir = std::env::temp_dir();
        let bam_path = temp_dir.join(format!("{}.bam", Uuid::new_v4()));
        let fasta_path = temp_dir.join(format!("{}.fa", Uuid::new_v4()));

        let config: SimulationConfig = serde_json::from_str(invalid_json).unwrap();
        let result = run(config, &bam_path, &fasta_path);
        // With empty reads, this should succeed but produce an empty BAM (valid)
        // So we won't assert error here, just test it doesn't crash
        drop(result);
        let bai_path = bam_path.with_extension("bam.bai");
        drop(std::fs::remove_file(&bam_path));
        drop(std::fs::remove_file(&fasta_path));
        drop(std::fs::remove_file(&bai_path));
    }

    /// Tests multiple read groups in BAM generation
    #[test]
    fn multiple_read_groups_work() {
        let config_json = r#"{
            "contigs": {
                "number": 2,
                "len_range": [100, 200]
            },
            "reads": [
                {
                    "number": 50,
                    "mapq_range": [10, 20],
                    "base_qual_range": [20, 30],
                    "len_range": [0.1, 0.5]
                },
                {
                    "number": 75,
                    "mapq_range": [30, 40],
                    "base_qual_range": [25, 35],
                    "len_range": [0.3, 0.7]
                },
                {
                    "number": 25,
                    "mapq_range": [5, 15],
                    "base_qual_range": [15, 25],
                    "len_range": [0.2, 0.6]
                }
            ]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        // Should have 50 + 75 + 25 = 150 reads total
        assert_eq!(reader.records().count(), 150);

        // Verify read groups exist in header
        let mut reader2 = bam::Reader::from_path(sim.bam_path()).unwrap();
        let header = reader2.header();
        let header_text = std::str::from_utf8(header.as_bytes()).unwrap();
        assert!(header_text.contains("@RG\tID:0"));
        assert!(header_text.contains("@RG\tID:1"));
        assert!(header_text.contains("@RG\tID:2"));

        // Count reads per read group and verify read name format
        let mut rg_counts = [0, 0, 0];
        for record in reader2.records() {
            let read = record.unwrap();
            let qname = std::str::from_utf8(read.qname()).unwrap();

            if let Ok(Aux::String(rg)) = read.aux(b"RG") {
                // Verify read name format: should be "rg.uuid"
                let parts: Vec<&str> = qname.split('.').collect();
                assert_eq!(parts.len(), 2, "Read name should be in format 'n.uuid'");

                let read_group_prefix =
                    parts.first().expect("parts should have at least 1 element");
                let uuid_part = parts.get(1).expect("parts should have 2 elements");

                assert_eq!(
                    *read_group_prefix, rg,
                    "Read name prefix should match read group"
                );

                // Verify the second part is a valid UUID
                assert!(
                    Uuid::parse_str(uuid_part).is_ok(),
                    "Read name should contain a valid UUID after the dot"
                );

                match rg {
                    "0" => *rg_counts.get_mut(0).unwrap() += 1,
                    "1" => *rg_counts.get_mut(1).unwrap() += 1,
                    "2" => *rg_counts.get_mut(2).unwrap() += 1,
                    unexpected => unreachable!("Unexpected read group: {unexpected}"),
                }
            }
        }
        assert_eq!(rg_counts[0], 50);
        assert_eq!(rg_counts[1], 75);
        assert_eq!(rg_counts[2], 25);
    }

    /// Tests that read sequences are valid substrings of their parent contigs
    #[expect(
        clippy::cast_sign_loss,
        reason = "tid and pos are non-negative in valid BAM"
    )]
    #[expect(
        clippy::cast_possible_truncation,
        reason = "tid fits in usize for normal BAM files"
    )]
    #[test]
    fn read_sequences_match_contigs() {
        let contigs = vec![
            ContigBuilder::default()
                .name("chr1")
                .seq("ACGTACGTACGTACGTACGTACGTACGTACGT".into())
                .build()
                .unwrap(),
            ContigBuilder::default()
                .name("chr2")
                .seq("TGCATGCATGCATGCATGCATGCATGCATGCA".into())
                .build()
                .unwrap(),
        ];

        let read_config = ReadConfigBuilder::default()
            .number(50)
            .len_range((0.2, 0.8))
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads = generate_reads_denovo(&contigs, &read_config, "test", &mut rng).unwrap();

        let mut validated_count = 0;
        for read in &reads {
            // Only validate forward mapped reads without soft clips for simplicity
            if !read.is_unmapped() && !read.is_reverse() {
                let cigar = read.cigar();

                // Skip reads with soft clips (shouldn't happen without barcodes, but be safe)
                let has_soft_clip = cigar.iter().any(|op| matches!(op, Cigar::SoftClip(_)));
                if has_soft_clip {
                    continue;
                }

                let tid = read.tid() as usize;
                let pos = read.pos() as usize;
                let contig = contigs.get(tid).expect("valid tid");
                let contig_seq = contig.get_dna_restrictive().get();

                // Get alignment length
                let mut aligned_len = 0usize;
                for op in &cigar {
                    if let Cigar::Match(len) = *op {
                        aligned_len = aligned_len.checked_add(len as usize).expect("overflow");
                    }
                }

                let read_seq = read.seq().as_bytes();
                let expected_seq = contig_seq
                    .get(pos..pos.checked_add(aligned_len).expect("overflow"))
                    .expect("contig subsequence exists");

                assert_eq!(
                    read_seq, expected_seq,
                    "Forward read sequence should exactly match contig substring"
                );
                validated_count += 1;
            }
        }

        // Ensure we validated at least some reads
        assert!(
            validated_count > 0,
            "Should have validated at least some forward reads"
        );
    }

    /// Tests different read states (unmapped, secondary, supplementary)
    #[test]
    fn different_read_states_work() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [200, 200]
            },
            "reads": [{
                "number": 1000,
                "mapq_range": [10, 20],
                "base_qual_range": [20, 30],
                "len_range": [0.2, 0.8]
            }]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        let mut has_unmapped = false;
        let mut has_forward = false;
        let mut has_reverse = false;
        let mut has_secondary = false;
        let mut has_supplementary = false;

        for record in reader.records() {
            let read = record.unwrap();

            if read.is_unmapped() {
                has_unmapped = true;
                // Verify unmapped read properties
                assert_eq!(read.tid(), -1);
                assert_eq!(read.pos(), -1);
                assert_eq!(read.mapq(), 255);
            } else {
                if read.is_reverse() {
                    has_reverse = true;
                } else {
                    has_forward = true;
                }

                if read.is_secondary() {
                    has_secondary = true;
                }

                if read.is_supplementary() {
                    has_supplementary = true;
                }
            }
        }

        // With 1000 reads, we should have diverse read states
        assert!(has_unmapped, "Should have unmapped reads");
        assert!(has_forward, "Should have forward reads");
        assert!(has_reverse, "Should have reverse reads");
        assert!(has_secondary, "Should have secondary reads");
        assert!(has_supplementary, "Should have supplementary reads");
    }

    /// Tests read length at 100% of contig length
    #[test]
    fn read_length_full_contig_works() {
        let contigs = vec![
            ContigBuilder::default()
                .name("chr1")
                .seq("ACGTACGTACGTACGTACGTACGTACGTACGT".into())
                .build()
                .unwrap(),
        ];

        let config_full_length = ReadConfigBuilder::default()
            .number(20)
            .len_range((1.0, 1.0))
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads_full =
            generate_reads_denovo(&contigs, &config_full_length, "test", &mut rng).unwrap();

        // All mapped reads should be exactly contig length
        for read in &reads_full {
            if !read.is_unmapped() {
                assert_eq!(read.seq_len(), 32, "Read should be full contig length");
            }
        }
    }

    /// Tests read length with very small fraction of contig
    #[test]
    fn read_length_small_fraction_works() {
        // Use 200bp contig so 1% = 2bp (won't round to 0)
        let contigs = [ContigBuilder::default()
            .name("chr1")
            .seq("ACGT".repeat(50))
            .build()
            .unwrap()];

        let config_small = ReadConfigBuilder::default()
            .number(20)
            .len_range((0.01, 0.05))
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads_small = generate_reads_denovo(&contigs, &config_small, "test", &mut rng).unwrap();

        // All mapped reads should be very small (2-10 bp given 200bp contig)
        for read in &reads_small {
            if !read.is_unmapped() {
                assert!(read.seq_len() <= 10, "Read should be very small");
                assert!(read.seq_len() >= 2, "Read should be at least 2bp");
            }
        }
    }
}

#[cfg(test)]
mod read_generation_barcodes {
    use super::*;
    use rust_htslib::bam::Read as _;

    /// Tests `add_barcode` function with forward and reverse reads
    #[expect(
        clippy::shadow_unrelated,
        reason = "repetition is fine; each block is clearly separated"
    )]
    #[test]
    fn add_barcode_works() {
        let read_seq = b"GGGGGGGG".to_vec();
        let barcode = DNARestrictive::from_str("ACGTAA").unwrap();

        // Test forward read: barcode + seq + revcomp(barcode)
        let result = add_barcode(&read_seq, barcode.clone(), ReadState::PrimaryFwd);
        assert_eq!(result, b"ACGTAAGGGGGGGGTTACGT".to_vec());

        // Test reverse read: comp(barcode) + seq + rev(barcode)
        let result = add_barcode(&read_seq, barcode, ReadState::PrimaryRev);
        assert_eq!(result, b"TGCATTGGGGGGGGAATGCA".to_vec());
    }

    /// Tests CIGAR string validity with and without barcodes
    #[test]
    fn cigar_strings_valid_with_or_without_barcodes() {
        // Test without barcodes
        let contigs = [ContigBuilder::default()
            .name("chr1")
            .seq("ACGTACGTACGTACGTACGTACGTACGTACGT".into())
            .build()
            .unwrap()];

        let config_no_barcode = ReadConfigBuilder::default()
            .number(20)
            .len_range((0.3, 0.7))
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads_no_barcode =
            generate_reads_denovo(&contigs, &config_no_barcode, "test", &mut rng).unwrap();

        for read in &reads_no_barcode {
            if !read.is_unmapped() {
                let cigar = read.cigar();
                // Without barcode, CIGAR should be just a single Match operation
                assert_eq!(cigar.len(), 1);
                assert!(matches!(cigar.first().unwrap(), Cigar::Match(_)));

                // Verify CIGAR length matches sequence length
                let cigar_len: u32 = cigar
                    .iter()
                    .map(|op| match *op {
                        Cigar::Match(len) | Cigar::SoftClip(len) => len,
                        Cigar::Ins(_)
                        | Cigar::Del(_)
                        | Cigar::RefSkip(_)
                        | Cigar::HardClip(_)
                        | Cigar::Pad(_)
                        | Cigar::Equal(_)
                        | Cigar::Diff(_) => unreachable!(),
                    })
                    .sum();
                assert_eq!(cigar_len as usize, read.seq_len());
            }
        }

        // Test with barcodes
        let config_with_barcode = ReadConfigBuilder::default()
            .number(20)
            .len_range((0.3, 0.7))
            .barcode("ACGTAA".into())
            .build()
            .unwrap();

        let reads_with_barcode =
            generate_reads_denovo(&contigs, &config_with_barcode, "test", &mut rng).unwrap();

        for read in &reads_with_barcode {
            if !read.is_unmapped() {
                let cigar = read.cigar();
                // With barcode, CIGAR should be: SoftClip + Match + SoftClip
                assert_eq!(cigar.len(), 3);
                assert!(matches!(cigar.first().unwrap(), Cigar::SoftClip(6))); // barcode length
                assert!(matches!(cigar.get(1).unwrap(), Cigar::Match(_)));
                assert!(matches!(cigar.get(2).unwrap(), Cigar::SoftClip(6))); // barcode length

                // Verify total CIGAR length matches sequence length
                let cigar_len: u32 = cigar
                    .iter()
                    .map(|op| match *op {
                        Cigar::Match(len) | Cigar::SoftClip(len) => len,
                        Cigar::Ins(_)
                        | Cigar::Del(_)
                        | Cigar::RefSkip(_)
                        | Cigar::HardClip(_)
                        | Cigar::Pad(_)
                        | Cigar::Equal(_)
                        | Cigar::Diff(_) => unreachable!(),
                    })
                    .sum();
                assert_eq!(cigar_len as usize, read.seq_len());
            }
        }
    }

    /// Tests read generation with barcode
    #[test]
    fn generate_reads_denovo_with_barcode_works() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [20, 20]
            },
            "reads": [{
                "number": 10,
                "len_range": [0.2, 0.8],
                "barcode": "GTACGG"
            }]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        for record in reader.records() {
            let read = record.unwrap();
            let seq = read.seq().as_bytes();
            let seq_len = seq.len();

            if read.is_reverse() {
                // Reverse: comp(GTACGG)=CATGCC at start, rev(GTACGG)=GGCATG at end
                assert_eq!(seq.get(..6).expect("seq has at least 6 bases"), b"CATGCC");
                assert_eq!(
                    seq.get(seq_len.saturating_sub(6)..)
                        .expect("seq has at least 6 bases"),
                    b"GGCATG"
                );
            } else {
                // Forward: GTACGG at start, revcomp(GTACGG)=CCGTAC at end
                assert_eq!(seq.get(..6).expect("seq has at least 6 bases"), b"GTACGG");
                assert_eq!(
                    seq.get(seq_len.saturating_sub(6)..)
                        .expect("seq has at least 6 bases"),
                    b"CCGTAC"
                );
            }
        }
    }
}

#[cfg(test)]
mod read_generation_with_mods_tests {
    use super::*;
    use crate::{CurrRead, ThresholdState, curr_reads_to_dataframe};
    use rust_htslib::bam::Read as _;

    /// Tests read generation with desired properties but with modifications
    #[test]
    fn generate_reads_denovo_with_mods_works() {
        let mut rng = rand::rng();
        let contigs = vec![
            ContigBuilder::default()
                .name("contig_0")
                .seq("ACGTACGTACGTACGTACGT".into())
                .build()
                .unwrap(),
            ContigBuilder::default()
                .name("contig_1")
                .seq("TGCATGCATGCATGCATGCA".into())
                .build()
                .unwrap(),
        ];

        let config = ReadConfigBuilder::default()
            .number(10000)
            .mapq_range((10, 20))
            .base_qual_range((30, 50))
            .len_range((0.2, 0.8))
            .mods(
                [ModConfigBuilder::default()
                    .base('C')
                    .mod_code("m".into())
                    .win([4].into())
                    .mod_range([(0f32, 1f32)].into())
                    .build()
                    .unwrap()]
                .into(),
            )
            .build()
            .unwrap();

        let reads = generate_reads_denovo(&contigs, &config, "1", &mut rng).unwrap();
        assert_eq!(reads.len(), 10000);

        let mut zero_to_255_visited = vec![false; 256];

        for read in &reads {
            // check mapping information
            if !read.is_unmapped() {
                assert!((10..=20).contains(&read.mapq()));
                assert!((0..2).contains(&read.tid()));
            }

            // check other information
            assert!((4..=16).contains(&read.seq_len()));
            assert!(read.qual().iter().all(|x| (30..=50).contains(x)));

            // check modification information
            let Aux::String(mod_pos_mm_tag) = read.aux(b"MM").unwrap() else {
                unreachable!()
            };
            let Aux::ArrayU8(mod_prob_ml_tag) = read.aux(b"ML").unwrap() else {
                unreachable!()
            };
            // Parse and verify the actual gap position values in MM tag
            let pos: Vec<&str> = mod_pos_mm_tag
                .strip_prefix("C+m?,")
                .unwrap()
                .strip_suffix(';')
                .unwrap()
                .split(',')
                .collect();
            assert!(pos.iter().all(|&x| x == "0"), "All MM values should be 0");

            // verify probability values which should have been converted to 0-255.
            #[expect(
                clippy::indexing_slicing,
                reason = "we are not gonna bother, this should be fine"
            )]
            for k in 0..mod_prob_ml_tag.len() {
                zero_to_255_visited[usize::from(mod_prob_ml_tag.get(k).expect("no error"))] = true;
            }
        }

        // check that all values from 0-255 have been visited as we are using a huge number of
        // reads.
        assert!(zero_to_255_visited.into_iter().all(|x| x));
    }

    /// Tests `TempBamSimulation` struct functionality with mods
    #[test]
    fn temp_bam_simulation_struct_with_mods() {
        let config_json = r#"{
            "contigs": {
                "number": 2,
                "len_range": [100, 200]
            },
            "reads": [{
                "number": 1000,
                "mapq_range": [10, 20],
                "base_qual_range": [10, 20],
                "len_range": [0.1, 0.8],
                "mods": [{
                    "base": "T",
                    "is_strand_plus": true,
                    "mod_code": "T",
                    "win": [4, 5],
                    "mod_range": [[0.1, 0.2], [0.3, 0.4]]
                }]
            }]
        }"#;

        // Create temporary simulation
        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();

        // Verify files exist
        assert!(Path::new(sim.bam_path()).exists());
        assert!(Path::new(sim.fasta_path()).exists());

        // Read BAM file and check contig, read count
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();
        let header = reader.header();
        assert_eq!(header.target_count(), 2);
        assert_eq!(reader.records().count(), 1000);
    }

    /// Tests `generate_random_dna_modification` with empty mod config
    #[test]
    fn generate_random_dna_modification_empty_config() {
        let seq = DNARestrictive::from_str("ACGTACGT").unwrap();
        let mod_configs: Vec<ModConfig> = vec![];
        let mut rng = rand::rng();

        let (mm_str, ml_vec) = generate_random_dna_modification(&mod_configs, &seq, &mut rng);

        assert_eq!(mm_str, String::new());
        assert_eq!(ml_vec.len(), 0);
    }

    /// Tests `generate_random_dna_modification` with single modification config
    #[test]
    fn generate_random_dna_modification_single_mod() {
        let seq = DNARestrictive::from_str("ACGTCGCGATCG").unwrap();
        let mod_config = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win(vec![2])
            .mod_range(vec![(0.5, 0.5)])
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // Sequence has 4 C's, so we expect 4 modifications
        assert_eq!(ml_vec.len(), 4);
        // All should be 128 (0.5 * 255)
        assert!(ml_vec.iter().all(|&x| x == 128u8));
        // All should be zero
        let probs: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(probs.len(), 4);
        assert!(probs.iter().all(|&x| x == "0"));
    }

    /// Tests `generate_random_dna_modification` with multiple modification configs
    #[test]
    fn generate_random_dna_modification_multiple_mods() {
        let seq = DNARestrictive::from_str("ACGTACGT").unwrap();

        let mod_config_c = ModConfigBuilder::default()
            .base('C')
            .mod_code('m'.into())
            .win(vec![1])
            .mod_range(vec![(0.8, 0.8)])
            .build()
            .unwrap();

        let mod_config_t = ModConfigBuilder::default()
            .base('T')
            .is_strand_plus(false)
            .mod_code('t'.into())
            .win(vec![1])
            .mod_range(vec![(0.4, 0.4)])
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) =
            generate_random_dna_modification(&[mod_config_c, mod_config_t], &seq, &mut rng);

        // Sequence has 2 C's and 2 T's
        assert!(mm_str.contains("C+m?,"));
        assert!(mm_str.contains("T-t?,"));
        assert_eq!(
            ml_vec,
            vec![204u8, 204u8, 102u8, 102u8],
            "ML values should be 204,204,102,102"
        );

        // Parse and verify the C modifications
        let c_section = mm_str
            .split(';')
            .find(|s| s.starts_with("C+m?"))
            .expect("Should have C+m? section");
        let c_probs: Vec<&str> = c_section
            .strip_prefix("C+m?,")
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(
            c_probs.len(),
            2,
            "Should have exactly 2 C modifications in ACGTACGT"
        );
        // All C pos should be 0
        assert!(
            c_probs.iter().all(|&x| x == "0"),
            "All C modifications should have gap pos 0",
        );

        // Parse and verify the T modifications
        let t_section = mm_str
            .split(';')
            .find(|s| s.starts_with("T-t?"))
            .expect("Should have T-t? section");
        let t_probs: Vec<&str> = t_section
            .strip_prefix("T-t?,")
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(
            t_probs.len(),
            2,
            "Should have exactly 2 T modifications in ACGTACGT"
        );
        // All T pos should be 0
        assert!(
            t_probs.iter().all(|&x| x == "0"),
            "All T modifications should have a gap pos of 0"
        );
    }

    /// Tests `generate_random_dna_modification` with N base (all bases)
    #[test]
    fn generate_random_dna_modification_n_base() {
        let seq = DNARestrictive::from_str("ACGT").unwrap();

        let mod_config = ModConfigBuilder::default()
            .base('N')
            .is_strand_plus(true)
            .mod_code("n".into())
            .win([4].into())
            .mod_range([(0.5, 0.5)].into())
            .build()
            .unwrap();
        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // N base means all 4 bases should be marked
        assert_eq!(ml_vec.len(), 4);
        // Parse and verify the actual pos values in MM tag
        let pos: Vec<&str> = mm_str
            .strip_prefix("N+n?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(pos.len(), 4, "Should have exactly 4 modifications for ACGT");

        // All positions should be 0
        assert!(
            pos.iter().all(|&x| x == "0"),
            "All N base modifications should have 0 as their gap position coordinate"
        );

        // Verify all ML values are 128 (probabilities)
        assert_eq!(
            ml_vec,
            vec![128u8, 128u8, 128u8, 128u8],
            "All ML values should be 128 and number of values is 4"
        );
    }

    /// Tests `generate_random_dna_modification` with cycling windows
    #[test]
    fn generate_random_dna_modification_cycling_windows() {
        let seq = DNARestrictive::from_str("CCCCCCCCCCCCCCCC").unwrap(); // 16 C's

        let mod_config = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win([3, 2].into())
            .mod_range([(0.8, 0.8), (0.4, 0.4)].into())
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // Should have 16 modifications, cycling pattern: 3@0.8, 2@0.4, 3@0.8, 2@0.4, ...
        let pos: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(pos, vec!["0"; 16]);
        // Verify the cycling pattern (0.8 = 204, 0.4 = 102)
        let expected_pattern: Vec<u8> = vec![
            204, 204, 204, 102, 102, 204, 204, 204, 102, 102, 204, 204, 204, 102, 102, 204,
        ];
        assert_eq!(ml_vec, expected_pattern);
    }
    /// Tests multiple simultaneous modifications on different bases
    #[expect(
        clippy::similar_names,
        reason = "has_c_mod, has_a_mod, has_t_mod are clear in context"
    )]
    #[test]
    fn multiple_simultaneous_modifications_work() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [100, 100],
                "repeated_seq": "ACGTACGTACGTACGT"
            },
            "reads": [{
                "number": 20,
                "mapq_range": [20, 30],
                "base_qual_range": [20, 30],
                "len_range": [0.8, 1.0],
                "mods": [
                    {
                        "base": "C",
                        "is_strand_plus": true,
                        "mod_code": "m",
                        "win": [2],
                        "mod_range": [[0.7, 0.9]]
                    },
                    {
                        "base": "A",
                        "is_strand_plus": true,
                        "mod_code": "a",
                        "win": [3],
                        "mod_range": [[0.3, 0.5]]
                    },
                    {
                        "base": "T",
                        "is_strand_plus": false,
                        "mod_code": "t",
                        "win": [1],
                        "mod_range": [[0.5, 0.6]]
                    }
                ]
            }]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        let mut has_c_mod = false;
        let mut has_a_mod = false;
        let mut has_t_mod = false;

        for record in reader.records() {
            let read = record.unwrap();
            if let Ok(Aux::String(mm_tag)) = read.aux(b"MM") {
                // Check that all three modification types are present
                if mm_tag.contains("C+m?") {
                    has_c_mod = true;
                }
                if mm_tag.contains("A+a?") {
                    has_a_mod = true;
                }
                if mm_tag.contains("T-t?") {
                    has_t_mod = true;
                }

                // Verify ML tag exists and has correct format
                assert!(
                    matches!(read.aux(b"ML").unwrap(), Aux::ArrayU8(_)),
                    "ML tag should be ArrayU8"
                );
            }
        }

        assert!(has_c_mod, "Should have C+m modifications");
        assert!(has_a_mod, "Should have A+a modifications");
        assert!(has_t_mod, "Should have T-t modifications");
    }

    /// Tests that modifications only target the specified bases
    #[expect(
        clippy::shadow_unrelated,
        reason = "clear variable reuse in sequential tests"
    )]
    #[test]
    fn modifications_target_correct_bases() {
        // Create sequence with known base counts
        let seq = DNARestrictive::from_str("AAAACCCCGGGGTTTT").unwrap();

        // template we will reuse for various mods
        let mod_config_template = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win([4].into())
            .mod_range([(1.0, 1.0)].into());

        // Test C modification - should only mark C bases
        let mod_config_c = mod_config_template.clone().build().unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_c], &seq, &mut rng);

        // Sequence has exactly 4 C's, so should have 4 modifications
        assert_eq!(ml_vec.len(), 4);
        let probs: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(probs.len(), 4, "Should have exactly 4 C modifications");

        // Test T modification - should only mark T bases
        let mod_config_t = mod_config_template
            .clone()
            .base('T')
            .is_strand_plus(false)
            .mod_code("t".into())
            .build()
            .unwrap();

        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_t], &seq, &mut rng);

        // Sequence has exactly 4 T's, so should have 4 modifications
        assert_eq!(ml_vec.len(), 4);
        let probs: Vec<&str> = mm_str
            .strip_prefix("T-t?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(probs.len(), 4, "Should have exactly 4 T modifications");

        // Test A modification - should only mark A bases
        let mod_config_a = mod_config_template
            .clone()
            .base('A')
            .mod_code("a".into())
            .build()
            .unwrap();

        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_a], &seq, &mut rng);

        // Sequence has exactly 4 A's, so should have 4 modifications
        assert_eq!(ml_vec.len(), 4);
        let probs: Vec<&str> = mm_str
            .strip_prefix("A+a?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(probs.len(), 4, "Should have exactly 4 A modifications");

        // Test G modification - should only mark G bases
        let mod_config_g = mod_config_template
            .clone()
            .base('G')
            .mod_code("g".into())
            .build()
            .unwrap();

        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_g], &seq, &mut rng);

        // Sequence has exactly 4 G's, so should have 4 modifications
        assert_eq!(ml_vec.len(), 4);
        let probs: Vec<&str> = mm_str
            .strip_prefix("G+g?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(probs.len(), 4, "Should have exactly 4 G modifications");
    }

    /// Tests edge case: sequence with no target base for modification
    #[test]
    fn edge_case_no_target_base_for_modification() {
        let seq = DNARestrictive::from_str("AAAAAAAAAA").unwrap(); // Only A's

        let mod_config = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win([5].into())
            .mod_range([(0.5, 0.5)].into())
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // Should have no modifications since no C's exist
        assert_eq!(mm_str, String::new());
        assert_eq!(ml_vec.len(), 0);
    }

    /// Tests edge case: modification with probability 0.0 and 1.0
    #[expect(
        clippy::shadow_unrelated,
        reason = "clear variable reuse in sequential tests"
    )]
    #[test]
    fn edge_case_modification_probability_extremes() {
        let seq = DNARestrictive::from_str("CCCCCCCC").unwrap();

        // template to build modification configurations
        let mod_config_template = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win([8].into());

        let mod_config_zero = mod_config_template
            .clone()
            .mod_range([(0.0, 0.0)].into())
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_zero], &seq, &mut rng);

        assert_eq!(ml_vec, vec![0u8; 8]);
        let pos: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert!(pos.iter().all(|&x| x == "0"));

        // Test probability 1.0
        let mod_config_one = mod_config_template
            .clone()
            .mod_range([(1.0, 1.0)].into())
            .build()
            .unwrap();

        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config_one], &seq, &mut rng);

        assert_eq!(ml_vec, vec![255u8; 8]);
        let pos: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert!(pos.iter().all(|&x| x == "0"));
    }

    /// Tests config deserialization from JSON string with mods
    #[expect(
        clippy::indexing_slicing,
        reason = "test validates length before indexing"
    )]
    #[test]
    fn config_deserialization_works_with_json_with_mods() {
        // Create a JSON config string
        let json_str = r#"{
            "contigs": {
                "number": 5,
                "len_range": [100, 500],
                "repeated_seq": "ACGTACGT"
            },
            "reads": [
                {
                    "number": 100,
                    "mapq_range": [10, 30],
                    "base_qual_range": [20, 40],
                    "len_range": [0.1, 0.9],
                    "barcode": "ACGTAA",
                    "mods": [{
                        "base": "C",
                        "is_strand_plus": true,
                        "mod_code": "m",
                        "win": [5, 3],
                        "mod_range": [[0.3, 0.7], [0.1, 0.5]]
                    }]
                },
                {
                    "number": 50,
                    "mapq_range": [5, 15],
                    "base_qual_range": [15, 25],
                    "len_range": [0.2, 0.8]
                }
            ]
        }"#;

        // Deserialize
        let config: SimulationConfig = serde_json::from_str(json_str).unwrap();

        // Verify all fields deserialized correctly
        assert_eq!(config.contigs.number.get(), 5);
        assert_eq!(config.contigs.len_range.low().get(), 100);
        assert_eq!(config.contigs.len_range.high().get(), 500);
        assert!(config.contigs.repeated_seq.is_some());

        assert_eq!(config.reads.len(), 2);

        // Verify first read config
        assert_eq!(config.reads[0].number.get(), 100);
        assert_eq!(config.reads[0].mapq_range.low(), 10);
        assert_eq!(config.reads[0].mapq_range.high(), 30);
        assert_eq!(config.reads[0].base_qual_range.low(), 20);
        assert_eq!(config.reads[0].base_qual_range.high(), 40);
        assert!(config.reads[0].barcode.is_some());
        assert_eq!(config.reads[0].mods.len(), 1);
        assert!(matches!(config.reads[0].mods[0].base, AllowedAGCTN::C));
        assert_eq!(config.reads[0].mods[0].win.len(), 2);

        // Verify second read config
        assert_eq!(config.reads[1].number.get(), 50);
        assert_eq!(config.reads[1].mods.len(), 0);
        assert!(config.reads[1].barcode.is_none());
    }

    /// Tests that modifications are applied to barcode bases
    /// Creates a sequence with no C's, but barcode has C's, so modifications should appear
    #[test]
    fn barcodes_with_modifications_integration_works() {
        // Create contig with only A's (no C's)
        let contigs = [ContigBuilder::default()
            .name("chr1")
            .seq("A".repeat(50))
            .build()
            .unwrap()];

        let config = ReadConfigBuilder::default()
            .number(20)
            .len_range((0.3, 0.7))
            .barcode("ACGTAA".into()) // barcode contains Cs i.e. barcode sequence has one C
            .mods(
                [ModConfigBuilder::default()
                    .base('C')
                    .mod_code("m".into())
                    .win([10].into())
                    .mod_range([(0.8, 0.8)].into())
                    .build()
                    .unwrap()]
                .into(),
            )
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads = generate_reads_denovo(&contigs, &config, "test", &mut rng).unwrap();

        let mut has_modifications = false;
        for read in &reads {
            if !read.is_unmapped() {
                // The read sequence should have barcodes added
                // Forward: ACGTAA + AAAAA... + TTACGT (barcode has 1 C, rev comp has 0 C)
                // Reverse: TGCATT + AAAAA... + AATGCA (complement has 1 C, reverse has 0 C)
                // So each read should have at least 1 C from the barcode

                let mm_pos_result = read.aux(b"MM");
                let ml_prob_result = read.aux(b"ML");

                // Should have MM and ML tags because barcode introduced C's
                assert!(
                    mm_pos_result.is_ok(),
                    "MM tag should be present due to C in barcode"
                );
                assert!(
                    ml_prob_result.is_ok(),
                    "ML tag should be present due to C in barcode"
                );

                if let Ok(Aux::String(mm_str)) = mm_pos_result {
                    assert!(
                        mm_str.starts_with("C+m?,"),
                        "MM tag should contain C+m modifications"
                    );
                    assert!(!mm_str.is_empty(), "MM tag should not be empty");
                    has_modifications = true;
                }
            }
        }

        assert!(
            has_modifications,
            "Should have found C modifications from barcode bases"
        );
    }

    /// Tests edge case: window size larger than number of target bases in sequence
    #[test]
    fn edge_case_window_larger_than_sequence() {
        let seq = DNARestrictive::from_str("ACGTACGT").unwrap(); // Only 2 C's

        let mod_config = ModConfigBuilder::default()
            .base('C')
            .mod_code("m".into())
            .win([100].into()) // window of 100 Cs but only 2Cs exist in the sequence.
            .mod_range([(0.5, 0.5)].into())
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // Should only generate modifications for the 2 C's that exist
        assert_eq!(
            ml_vec,
            vec![128u8, 128u8],
            "All prob should be 128 (0.5*255)"
        );
        let pos: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(pos.len(), 2, "Should have exactly 2 position values");
        assert!(pos.iter().all(|&x| x == "0"), "All pos should be 0");
    }

    /// Tests edge case: single-base windows with multiple cycles
    #[test]
    fn edge_case_single_base_windows() {
        let seq = DNARestrictive::from_str("C".repeat(16).as_str()).unwrap(); // 16 C's

        let mod_config = ModConfigBuilder::default()
            .base('C')
            .is_strand_plus(true)
            .mod_code("m".into())
            .win([1].into())
            .mod_range([(0.9, 0.9), (0.1, 0.1)].into())
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let (mm_str, ml_vec) = generate_random_dna_modification(&[mod_config], &seq, &mut rng);

        // Should have 16 modifications, alternating pattern: 0.9, 0.1, 0.9, 0.1, ...
        // Verify alternating pattern (0.9*255=229.5→230, 0.1*255=25.5→26)
        let expected_pattern: Vec<u8> = vec![
            230, 26, 230, 26, 230, 26, 230, 26, 230, 26, 230, 26, 230, 26, 230, 26,
        ];
        assert_eq!(ml_vec, expected_pattern);
        let pos: Vec<&str> = mm_str
            .strip_prefix("C+m?,")
            .unwrap()
            .strip_suffix(';')
            .unwrap()
            .split(',')
            .collect();
        assert_eq!(pos, vec!["0"; 16], "pos should have 16 entries, all 0");
    }

    /// Tests that modifications on reverse reads are correctly applied to reverse-complemented sequence
    #[test]
    fn reverse_reads_modification_positions_correct() {
        // Create sequence with 3 C's: "AAAAACAAAAACAAAAAC"
        let contigs = [ContigBuilder::default()
            .name("chr1")
            .seq("AAAAACAAAAACAAAAAC".into())
            .build()
            .unwrap()];

        let config = ReadConfigBuilder::default()
            .number(100)
            .len_range((1.0, 1.0))
            .mods(
                [ModConfigBuilder::default()
                    .base('C')
                    .mod_code("m".into())
                    .win([10].into())
                    .mod_range([(0.8, 0.8)].into())
                    .build()
                    .unwrap()]
                .into(),
            )
            .build()
            .unwrap();

        let mut rng = rand::rng();
        let reads = generate_reads_denovo(&contigs, &config, "test", &mut rng).unwrap();

        let mut forward_with_mods = 0;

        for read in &reads {
            if !read.is_unmapped() {
                let mm_result = read.aux(b"MM");

                if read.is_reverse() {
                    // Reverse complement of "AAAAACAAAAACAAAAAC"
                    // has 3 G's but 0 C's, so no C modifications should exist
                    assert!(
                        mm_result.is_err(),
                        "Reverse reads should have no MM tag (revcomp has no C's)"
                    );
                } else {
                    // Forward reads should have MM tag with 3 C modifications
                    assert!(mm_result.is_ok(), "Forward reads should have MM tag");
                    if let Ok(Aux::String(mm_str)) = mm_result {
                        // Parse and count modifications
                        let probs: Vec<&str> = mm_str
                            .strip_prefix("C+m?,")
                            .unwrap()
                            .strip_suffix(';')
                            .unwrap()
                            .split(',')
                            .collect();
                        assert_eq!(probs.len(), 3, "Should have exactly 3 C modifications");
                        forward_with_mods += 1;
                    }
                }
            }
        }

        assert!(
            forward_with_mods > 0,
            "Should have validated some forward reads with modifications"
        );
    }

    /// Tests that mismatches affect modification reference positions while preserving mod quality
    ///
    /// This test creates two read groups:
    /// - Group 0: 100% mod probability (quality 255), no mismatches - mods at expected C positions
    /// - Group 1: 51% mod probability (quality ~130), 100% mismatch - mods at shifted positions
    ///
    /// For a "ACGT" repeated contig, C's are at positions 1, 5, 9, 13, ... (form 4n+1).
    /// On reverse complement, G's become C's at positions 2, 6, 10, 14, ... (form 4n+2).
    /// With 100% mismatch, positions should be shifted and no longer follow these patterns.
    #[expect(
        clippy::too_many_lines,
        reason = "test requires setup, iteration, and multiple assertions for thorough validation"
    )]
    #[test]
    fn mismatch_mod_check() {
        let json_str = r#"{
            "contigs": {
                "number": 1,
                "len_range": [100, 100],
                "repeated_seq": "ACGT"
            },
            "reads": [
                {
                    "number": 100,
                    "len_range": [1.0, 1.0],
                    "mods": [{
                        "base": "C",
                        "is_strand_plus": true,
                        "mod_code": "m",
                        "win": [1],
                        "mod_range": [[1.0, 1.0]]
                    }]
                },
                {
                    "number": 100,
                    "len_range": [1.0, 1.0],
                    "mismatch": 1.0,
                    "mods": [{
                        "base": "C",
                        "is_strand_plus": true,
                        "mod_code": "m",
                        "win": [1],
                        "mod_range": [[0.51, 0.51]]
                    }]
                }
            ]
        }"#;

        let config: SimulationConfig = serde_json::from_str(json_str).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();

        let mut bam = bam::Reader::from_path(sim.bam_path()).unwrap();
        let mut df_collection = Vec::new();

        for k in bam.records() {
            let record = k.unwrap();
            let curr_read = CurrRead::default()
                .try_from_only_alignment(&record)
                .unwrap()
                .set_mod_data(&record, ThresholdState::GtEq(0), 0)
                .unwrap();
            df_collection.push(curr_read);
        }

        let df = curr_reads_to_dataframe(df_collection.as_slice()).unwrap();

        let read_id_col = df.column("read_id").unwrap().str().unwrap();
        let ref_position_col = df.column("ref_position").unwrap().i64().unwrap();
        let alignment_type_col = df.column("alignment_type").unwrap().str().unwrap();
        let mod_quality_col = df.column("mod_quality").unwrap().u32().unwrap();

        let mut row_count_0: usize = 0;
        let mut row_count_1: usize = 0;

        // Violation counters for debugging
        let mut group0_forward_position_violations: usize = 0;
        let mut group0_reverse_position_violations: usize = 0;
        let mut group0_unmapped_position_violations: usize = 0;
        let mut group0_quality_violations: usize = 0;
        let mut group1_forward_position_violations: usize = 0;
        let mut group1_reverse_position_violations: usize = 0;
        let mut group1_unmapped_position_violations: usize = 0;
        let mut group1_quality_violations: usize = 0;
        let mut read_id_violations: usize = 0;

        for i in 0..df.height() {
            let read_id = read_id_col.get(i).unwrap();
            let ref_position = ref_position_col.get(i).unwrap();
            let alignment_type = alignment_type_col.get(i).unwrap();
            let mod_quality = mod_quality_col.get(i).unwrap();

            if read_id.starts_with("0.") {
                // Group 0: no mismatch, mod positions should follow 4n+1 (forward) or 4n+2 (reverse)
                if alignment_type.contains("forward") {
                    if ref_position % 4 != 1 {
                        group0_forward_position_violations += 1;
                    }
                } else if alignment_type.contains("reverse") {
                    if ref_position % 4 != 2 {
                        group0_reverse_position_violations += 1;
                    }
                } else {
                    // unmapped reads should have ref_position of -1
                    if ref_position != -1 {
                        group0_unmapped_position_violations += 1;
                    }
                }
                if mod_quality != 255 {
                    group0_quality_violations += 1;
                }
                row_count_0 += 1;
            } else if read_id.starts_with("1.") {
                // Group 1: 100% mismatch, mod positions should NOT follow expected patterns
                if alignment_type.contains("forward") {
                    if ref_position % 4 == 1 {
                        group1_forward_position_violations += 1;
                    }
                } else if alignment_type.contains("reverse") {
                    if ref_position % 4 == 2 {
                        group1_reverse_position_violations += 1;
                    }
                } else {
                    // unmapped reads should have ref_position of -1
                    if ref_position != -1 {
                        group1_unmapped_position_violations += 1;
                    }
                }
                if mod_quality != 130 {
                    group1_quality_violations += 1;
                }
                row_count_1 += 1;
            } else {
                read_id_violations += 1;
            }
        }

        // Assert all violations are zero
        assert_eq!(
            group0_forward_position_violations, 0,
            "Group 0 forward: expected 0 position violations"
        );
        assert_eq!(
            group0_reverse_position_violations, 0,
            "Group 0 reverse: expected 0 position violations"
        );
        assert_eq!(
            group0_unmapped_position_violations, 0,
            "Group 0 unmapped: expected 0 position violations"
        );
        assert_eq!(
            group0_quality_violations, 0,
            "Group 0: expected 0 quality violations"
        );
        assert_eq!(
            group1_forward_position_violations, 0,
            "Group 1 forward: expected 0 position violations"
        );
        assert_eq!(
            group1_reverse_position_violations, 0,
            "Group 1 reverse: expected 0 position violations"
        );
        assert_eq!(
            group1_unmapped_position_violations, 0,
            "Group 1 unmapped: expected 0 position violations"
        );
        assert_eq!(
            group1_quality_violations, 0,
            "Group 1: expected 0 quality violations"
        );
        assert_eq!(read_id_violations, 0, "expected 0 read_id violations");
        assert!(
            row_count_0 > 0,
            "Should have processed some rows from group 0"
        );
        assert!(
            row_count_1 > 0,
            "Should have processed some rows from group 1"
        );
    }
}

#[cfg(test)]
mod contig_generation_tests {
    use super::*;
    use rust_htslib::bam::Read as _;

    /// Tests edge case: repeated sequence contig generation
    #[test]
    fn edge_case_repeated_sequence_exact_length() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [16, 16],
                "repeated_seq": "ACGT"
            },
            "reads": [{
                "number": 5,
                "len_range": [0.5, 0.5]
            }]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        // Verify contig is exactly ACGTACGTACGTACGT (4 repeats)
        let header = reader.header();
        assert_eq!(header.target_len(0).unwrap(), 16);
    }

    /// Tests edge case: minimum contig size (1 bp)
    #[test]
    fn edge_case_minimum_contig_size() {
        let config_json = r#"{
            "contigs": {
                "number": 1,
                "len_range": [1, 1]
            },
            "reads": [{
                "number": 10,
                "mapq_range": [10, 20],
                "base_qual_range": [20, 30],
                "len_range": [1.0, 1.0]
            }]
        }"#;

        let config: SimulationConfig = serde_json::from_str(config_json).unwrap();
        let sim = TempBamSimulation::new(config).unwrap();
        let mut reader = bam::Reader::from_path(sim.bam_path()).unwrap();

        // Verify 1bp contig works
        let header = reader.header();
        assert_eq!(header.target_count(), 1);
        assert_eq!(header.target_len(0).unwrap(), 1);

        // Some reads should exist (though some may be unmapped)
        assert!(reader.records().count() > 0);
    }

    /// Tests contig generation
    #[test]
    fn generate_contigs_denovo_works() {
        let config = ContigConfigBuilder::default()
            .number(5)
            .len_range((100, 200))
            .build()
            .unwrap();
        let contigs = generate_contigs_denovo(config.number, config.len_range, &mut rand::rng());
        assert_eq!(contigs.len(), 5);
        for (i, contig) in contigs.iter().enumerate() {
            assert_eq!(contig.name, format!("contig_0000{i}"));
            assert!((100..=200).contains(&contig.get_dna_restrictive().get().len()));
            for base in contig.get_dna_restrictive().get() {
                assert!([b'A', b'C', b'G', b'T'].contains(base));
            }
        }
    }

    /// Tests contig generation with repeated sequence
    #[test]
    fn generate_contigs_denovo_repeated_seq_works() {
        let seq = DNARestrictive::from_str("ACGT").unwrap();
        let contigs = generate_contigs_denovo_repeated_seq(
            NonZeroU32::new(10000).unwrap(),
            OrdPair::new(NonZeroU64::new(10).unwrap(), NonZeroU64::new(12).unwrap()).unwrap(),
            &seq,
            &mut rand::rng(),
        );

        let mut counts = [0, 0, 0];

        assert_eq!(contigs.len(), 10000);
        for (i, contig) in contigs.iter().enumerate() {
            assert_eq!(contig.name, format!("contig_{i:05}"));
            let idx = match contig.get_dna_restrictive().get() {
                b"ACGTACGTAC" => 0,
                b"ACGTACGTACG" => 1,
                b"ACGTACGTACGT" => 2,
                _ => unreachable!(),
            };
            *counts
                .get_mut(idx)
                .expect("idx is 0, 1, or 2; counts has 3 elements") += 1;
        }

        // 3000/10000 is quite lax actually - we expect ~3333 each
        for count in counts {
            assert!(count >= 3000);
        }
    }
}

/// Tests for `PerfectSeqMatchToNot` methods
#[cfg(test)]
mod perfect_seq_match_to_not_tests {
    use super::*;

    #[test]
    fn seq_with_valid_sequence() -> Result<(), Error> {
        let _builder = PerfectSeqMatchToNot::seq(b"ACGT".to_vec())?;
        Ok(())
    }

    #[test]
    fn seq_with_empty_sequence_returns_error() {
        let result = PerfectSeqMatchToNot::seq(b"".to_vec());
        assert!(matches!(result, Err(Error::InvalidState(_))));
    }

    #[test]
    fn build_without_barcode_forward_read() -> Result<(), Error> {
        let mut rng = rand::rng();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .build(ReadState::PrimaryFwd, &mut rng)?;
        assert_eq!(seq, b"GGGGGGGG");
        assert_eq!(cigar.expect("no error").to_string(), "8M");
        Ok(())
    }

    #[test]
    fn build_without_barcode_reverse_read() -> Result<(), Error> {
        let mut rng = rand::rng();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .build(ReadState::PrimaryRev, &mut rng)?;
        assert_eq!(seq, b"GGGGGGGG");
        assert_eq!(cigar.expect("no error").to_string(), "8M");
        Ok(())
    }

    #[test]
    fn build_with_barcode_forward_read() -> Result<(), Error> {
        let mut rng = rand::rng();
        let barcode = DNARestrictive::from_str("ACGTAA").unwrap();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .barcode(barcode)
            .build(ReadState::PrimaryFwd, &mut rng)?;
        assert_eq!(seq, b"ACGTAAGGGGGGGGTTACGT");
        assert_eq!(cigar.expect("no error").to_string(), "6S8M6S");
        Ok(())
    }

    #[test]
    fn build_with_barcode_reverse_read() -> Result<(), Error> {
        let mut rng = rand::rng();
        let barcode = DNARestrictive::from_str("ACGTAA").unwrap();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .barcode(barcode)
            .build(ReadState::PrimaryRev, &mut rng)?;
        assert_eq!(seq, b"TGCATTGGGGGGGGAATGCA");
        assert_eq!(cigar.expect("no error").to_string(), "6S8M6S");
        Ok(())
    }

    #[test]
    fn build_unmapped_read_returns_none_cigar() -> Result<(), Error> {
        let mut rng = rand::rng();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .build(ReadState::Unmapped, &mut rng)?;
        assert_eq!(seq, b"GGGGGGGG");
        assert!(cigar.is_none());
        Ok(())
    }

    #[test]
    fn build_unmapped_read_with_barcode_returns_none_cigar() -> Result<(), Error> {
        let mut rng = rand::rng();
        let barcode = DNARestrictive::from_str("ACGTAA").unwrap();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGG".to_vec())?
            .barcode(barcode)
            .build(ReadState::Unmapped, &mut rng)?;
        assert_eq!(seq, b"ACGTAAGGGGGGGGTTACGT");
        assert!(cigar.is_none());
        Ok(())
    }

    #[test]
    fn build_with_delete() -> Result<(), Error> {
        let mut rng = rand::rng();
        let delete_range = OrdPair::new(F32Bw0and1::try_from(0.5)?, F32Bw0and1::try_from(0.75)?)?;
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAATTTTCCCCGGGG".to_vec())?
            .delete(delete_range)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // Original: AAAATTTTCCCCGGGG (16 bases)
        // Delete 50%-75%: positions 8-12, deletes CCCC (4 bases)
        // Result: AAAATTTTGGGG (12 bases)
        assert_eq!(seq, b"AAAATTTTGGGG");
        assert_eq!(cigar.expect("no error").to_string(), "8M4D4M");
        Ok(())
    }

    #[test]
    fn build_with_insert_middle() -> Result<(), Error> {
        let mut rng = rand::rng();
        let insert_seq = DNARestrictive::from_str("TTTT").unwrap();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAGGGG".to_vec())?
            .insert_middle(insert_seq)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // Original: AAAAGGGG (8 bases)
        // Middle is at position 4
        // Insert TTTT at position 4
        // Result: AAAATTTTGGGG (12 bases)
        assert_eq!(seq, b"AAAATTTTGGGG");
        assert_eq!(cigar.expect("no error").to_string(), "4M4I4M");
        Ok(())
    }

    #[test]
    fn build_with_mismatch() -> Result<(), Error> {
        let mut rng = rand::rng();
        let mismatch_frac = F32Bw0and1::try_from(0.5)?;
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())?
            .mismatch(mismatch_frac)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // Original: AAAAAAAA (8 bases)
        // 50% mismatch = 4 bases should be changed
        // Count how many bases are NOT 'A'
        let mismatch_count = seq.iter().filter(|&&b| b != b'A').count();
        assert_eq!(mismatch_count, 4);

        // CIGAR should still be 8M (mismatches don't change CIGAR)
        assert_eq!(cigar.expect("no error").to_string(), "8M");
        Ok(())
    }

    #[test]
    fn build_with_delete_and_insert() -> Result<(), Error> {
        let mut rng = rand::rng();
        let delete_range = OrdPair::new(F32Bw0and1::try_from(0.5)?, F32Bw0and1::try_from(0.75)?)?;
        let insert_seq = DNARestrictive::from_str("TT").unwrap();
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAACCCCGGGG".to_vec())?
            .delete(delete_range)
            .insert_middle(insert_seq)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // Original: AAAACCCCGGGG (12 bases)
        // Mark positions 6-8 for deletion (CCG)
        // Insert TT at position 6 (middle of 12)
        // Final operations: 6M (AAAACC) + 2I (TT) + 3D (CCG) + 3M (GGG)
        // Result: AAAACCTTGGG (11 bases)
        assert_eq!(seq, b"AAAACCTTGGG");
        assert_eq!(cigar.expect("no error").to_string(), "6M2I3D3M");
        Ok(())
    }

    #[test]
    fn build_with_all_features() -> Result<(), Error> {
        let mut rng = rand::rng();
        let delete_range = OrdPair::new(F32Bw0and1::try_from(0.25)?, F32Bw0and1::try_from(0.5)?)?;
        let insert_seq = DNARestrictive::from_str("CC").unwrap();
        let mismatch_frac = F32Bw0and1::try_from(0.25)?;
        let barcode = DNARestrictive::from_str("AAA").unwrap();

        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"GGGGGGGGGGGGGGGG".to_vec())?
            .delete(delete_range)
            .insert_middle(insert_seq)
            .mismatch(mismatch_frac)
            .barcode(barcode)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // Original: GGGGGGGGGGGGGGGG (16 bases)
        // Mismatch 25% = 4 bases changed (but to C, T, or A)
        // Delete 25%-50%: positions 4-8, deletes GGGG (4 bases) -> 12 bases
        // Insert CC at middle (position 6) -> 14 bases
        // Add barcode AAA to both ends -> 20 bases total
        assert_eq!(seq.len(), 20);

        // CIGAR should have SoftClips, deletion, insertion, and matches
        let cigar_str = cigar.expect("no error").to_string();
        assert!(cigar_str.starts_with("3S")); // Barcode at start
        assert!(cigar_str.ends_with("3S")); // Barcode at end
        assert!(cigar_str.contains('D')); // Deletion
        assert!(cigar_str.contains('I')); // Insertion
        Ok(())
    }

    #[test]
    fn build_with_delete_zero_length() -> Result<(), Error> {
        let mut rng = rand::rng();
        // Delete nothing (start == end after rounding)
        let delete_range = OrdPair::new(F32Bw0and1::try_from(0.5)?, F32Bw0and1::try_from(0.5)?)?;
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())?
            .delete(delete_range)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // No deletion should occur
        assert_eq!(seq, b"AAAAAAAA");
        assert_eq!(cigar.expect("no error").to_string(), "8M");
        Ok(())
    }

    #[test]
    fn build_with_mismatch_zero_fraction() -> Result<(), Error> {
        let mut rng = rand::rng();
        let mismatch_frac = F32Bw0and1::try_from(0.0)?;
        let (seq, cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())?
            .mismatch(mismatch_frac)
            .build(ReadState::PrimaryFwd, &mut rng)?;

        // No mismatches should occur
        assert_eq!(seq, b"AAAAAAAA");
        assert_eq!(cigar.expect("no error").to_string(), "8M");
        Ok(())
    }

    #[test]
    #[should_panic(expected = "SimulateDNASeqCIGAREndProblem")]
    fn build_with_delete_whole_length() {
        let mut rng = rand::rng();
        let delete_range = OrdPair::new(F32Bw0and1::zero(), F32Bw0and1::one()).unwrap();
        let (_seq, _cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())
            .unwrap()
            .delete(delete_range)
            .build(ReadState::PrimaryFwd, &mut rng)
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "SimulateDNASeqCIGAREndProblem")]
    fn build_with_insert_almost_whole_length() {
        let mut rng = rand::rng();
        let insert_seq = DNARestrictive::from_str("AATT").unwrap();
        let (_seq, _cigar) = PerfectSeqMatchToNot::seq(b"A".to_vec())
            .unwrap()
            .insert_middle(insert_seq)
            .build(ReadState::PrimaryFwd, &mut rng)
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "SimulateDNASeqCIGAREndProblem")]
    fn build_with_delete_whole_length_with_barcode() {
        let mut rng = rand::rng();
        let delete_range = OrdPair::new(F32Bw0and1::zero(), F32Bw0and1::one()).unwrap();
        let barcode = DNARestrictive::from_str("CGCG").unwrap();
        let (_seq, _cigar) = PerfectSeqMatchToNot::seq(b"AAAAAAAA".to_vec())
            .unwrap()
            .delete(delete_range)
            .barcode(barcode)
            .build(ReadState::PrimaryFwd, &mut rng)
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "SimulateDNASeqCIGAREndProblem")]
    fn build_with_insert_almost_whole_length_with_barcode() {
        let mut rng = rand::rng();
        let insert_seq = DNARestrictive::from_str("AATT").unwrap();
        let barcode = DNARestrictive::from_str("CGCG").unwrap();
        let (_seq, _cigar) = PerfectSeqMatchToNot::seq(b"A".to_vec())
            .unwrap()
            .insert_middle(insert_seq)
            .barcode(barcode)
            .build(ReadState::PrimaryFwd, &mut rng)
            .unwrap();
    }
}