twitcher 0.8.1

Find template switch mutations in genomic data
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
use std::{collections::HashSet, ops::Range, sync::Arc};

use anyhow::{Context as _, bail};
use rust_htslib::bam::{self, FetchDefinition, Read as _};
use tracing::{error, warn};

use crate::{
    common::{bam_filters::BamFilters, coords::GenomeRegion},
    counter,
    vcf::pipeline::{clusterizer::phasing::GtAndPhase, record::InputRecord},
};

/// Confidence thresholds for local read-based phasing. These gate when an unphased
/// heterozygous record inside a cluster is allowed to be assigned to a haplotype from
/// read evidence. Only relevant when a phasing BAM (`--phasing-bam`) is supplied; a
/// record that clears neither gate stays unphased and continues to block its cluster.
#[derive(clap::Args, Debug, Clone)]
#[command(next_help_heading = "Phasing")]
pub struct PhasingSettings {
    /// Minimum number of reads that must support the winning haplotype assignment.
    /// Assignments backed by fewer reads are rejected, guarding against decisions made on
    /// too little coverage; the record then stays unphased.
    #[arg(
        long = "phasing-min-reads",
        value_name = "NUM",
        default_value_t = 3,
        requires = "phasing_bam"
    )]
    pub min_reads: u32,

    /// Minimum fraction of informative reads that must agree on the assignment [0.5–1.0].
    /// "Informative" means the read covers the position and carries a recognisable allele.
    /// Higher values reject conflicting or noisy evidence; lower values phase more
    /// aggressively. Records below this threshold remain unphased.
    #[arg(
        long = "phasing-confidence",
        value_name = "FRACTION",
        default_value_t = 0.8,
        requires = "phasing_bam"
    )]
    pub confidence: f64,

    /// Minimum read mapping quality (MAPQ) to use a read as phasing evidence. Reads below this
    /// are skipped entirely, so mis-mapped reads cannot contribute spurious allele calls.
    #[arg(
        long = "phasing-min-mapq",
        value_name = "NUM",
        default_value_t = 20,
        requires = "phasing_bam"
    )]
    pub min_mapq: u8,

    /// Minimum base quality (Phred) at the variant position for a read's allele call to count.
    /// A read whose base(s) at the locus fall below this are treated as uninformative there,
    /// so likely sequencing errors do not become votes. Deletions (no read base) are unaffected.
    #[arg(
        long = "phasing-min-base-qual",
        value_name = "NUM",
        default_value_t = 20,
        requires = "phasing_bam"
    )]
    pub min_base_qual: u8,

    #[command(flatten)]
    pub bam_filters: BamFilters,
}

impl Default for PhasingSettings {
    fn default() -> Self {
        Self {
            min_reads: 3,
            confidence: 0.8,
            min_mapq: 20,
            min_base_qual: 20,
            bam_filters: BamFilters::default(),
        }
    }
}

/// Phasing orientation chosen for an unphased record relative to its GT allele slots `[g0, g1]`.
/// `Direct` keeps the slot order (`g0` on H0, `g1` on H1 → written `g0|g1`); `Flipped` swaps it
/// (`g1` on H0, `g0` on H1 → written `g1|g0`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Orientation {
    Direct,
    Flipped,
}

/// Outcome of a per-record phasing decision, carrying the reason a record stayed unresolved
/// so it can be attributed to a granular counter (see [`record_outcome`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Decision {
    /// Assigned to a haplotype with the chosen orientation.
    Resolved(Orientation),
    /// No informative reads cover the record (missing evidence).
    NoEvidence,
    /// The winning orientation is supported by fewer than `min_reads` reads.
    InsufficientReads,
    /// Informative reads agree below the `confidence` threshold (conflict / noise).
    LowConfidence,
}

/// Increment the matching `phasing.records.*` counter for `decision` and map it to the
/// orientation to apply (`None` when the record stays unresolved).
fn record_outcome(decision: Decision, decisions: &mut Vec<Decision>) -> Option<Orientation> {
    decisions.push(decision);
    match decision {
        Decision::Resolved(o) => {
            counter!("phasing.records.resolved").inc(1);
            Some(o)
        }
        Decision::NoEvidence => {
            counter!("phasing.records.unresolved.no_evidence").inc(1);
            None
        }
        Decision::InsufficientReads => {
            counter!("phasing.records.unresolved.insufficient_reads").inc(1);
            None
        }
        Decision::LowConfidence => {
            counter!("phasing.records.unresolved.low_confidence").inc(1);
            None
        }
    }
}

/// A stretch of reference sequence together with the 0-based position of its first base.
///
/// Phasing needs the reference around a cluster to widen indel comparison spans across repeats
/// (see [`ambiguity_span`]) and to build the flanks of each allele's expected sequence.
#[derive(Clone, Copy, Debug)]
pub struct RefSlice<'a> {
    seq: &'a [u8],
    start: i64,
}

impl<'a> RefSlice<'a> {
    /// `seq` is the reference from `start` onwards. Bases are compared case-insensitively, so a
    /// soft-masked slice is fine.
    pub fn new(seq: &'a [u8], start: i64) -> Self {
        Self { seq, start }
    }

    /// The reference base at `pos`, or `None` outside the slice.
    fn base(&self, pos: i64) -> Option<u8> {
        let offset = usize::try_from(pos.checked_sub(self.start)?).ok()?;
        self.seq.get(offset).map(u8::to_ascii_uppercase)
    }

    /// Whether the two reference positions carry the same base. `None` at either position
    /// counts as "different", which stops a slide at the edge of the slice.
    fn same_base(&self, a: i64, b: i64) -> bool {
        matches!((self.base(a), self.base(b)), (Some(x), Some(y)) if x == y)
    }

    /// The reference over `range`, or `None` when the slice does not cover all of it.
    fn get(&self, range: Range<i64>) -> Option<&'a [u8]> {
        let lo = usize::try_from(range.start.checked_sub(self.start)?).ok()?;
        let hi = usize::try_from(range.end.checked_sub(self.start)?).ok()?;
        self.seq.get(lo..hi)
    }
}

/// How far an indel is allowed to slide while looking for equivalent placements. Bounds the
/// work in pathological repeats. A repeat that outruns it cannot be swallowed by the span, so a
/// read could spell the indel outside it and read back as REF; such a record is left unmatched
/// instead, which costs allele calls rather than correctness.
const MAX_INDEL_SLIDE: i64 = 100;

/// The minimal edit a `(REF, ALT)` pair describes once the bases both sides share at either end
/// are trimmed away. Only the two indel forms can sit at more than one reference position while
/// spelling the same haplotype, and only they need their comparison span widened.
#[derive(Debug, PartialEq, Eq)]
enum Edit<'a> {
    /// REF and ALT have equal length, so every allele base is claimed at a fixed position and
    /// only `at..at + len` actually differs. `len == 0` means REF and ALT are the same string.
    Substitution { at: i64, len: usize },
    /// `unit` is inserted immediately before reference position `at`.
    Insertion { at: i64, unit: &'a [u8] },
    /// `unit` is deleted from reference position `at` onwards.
    Deletion { at: i64, unit: &'a [u8] },
    /// Both sides non-empty and of different lengths; the trimmed REF bases `at..at + len` are
    /// replaced. Placement inside such an allele is not a simple slide, so these are not
    /// widened across repeats, only given a margin base on each side.
    Complex { at: i64, len: usize },
}

/// Reduce a `(REF, ALT)` pair at `pos` to its minimal edit by trimming the common suffix and
/// then the common prefix.
///
/// Trimming the suffix first matters: at `AAT -> AT` only that order exposes the deletion of a
/// single `A`. An allele pair that trims away entirely is not a variant and classifies as
/// [`Edit::Substitution`], which needs no widening.
// The trimmed prefix length is bounded by the allele length, which comes out of a VCF record and
// cannot approach `i64::MAX`.
#[allow(clippy::cast_possible_wrap)]
fn classify<'a>(pos: i64, ref_allele: &'a [u8], alt_allele: &'a [u8]) -> Edit<'a> {
    let suffix = ref_allele
        .iter()
        .rev()
        .zip(alt_allele.iter().rev())
        .take_while(|(r, a)| r.eq_ignore_ascii_case(a))
        .count();
    // `suffix` is at most the shorter allele's length, so neither subtraction can underflow.
    let r = ref_allele
        .get(..ref_allele.len() - suffix)
        .unwrap_or_default();
    let a = alt_allele
        .get(..alt_allele.len() - suffix)
        .unwrap_or_default();

    let k = r
        .iter()
        .zip(a)
        .take_while(|(r, a)| r.eq_ignore_ascii_case(a))
        .count();
    let (at, r, a) = (
        pos + k as i64,
        r.get(k..).unwrap_or_default(),
        a.get(k..).unwrap_or_default(),
    );

    match (r.is_empty(), a.is_empty()) {
        (true, true) => Edit::Substitution { at, len: 0 }, // REF == ALT: not a variant
        (true, false) => Edit::Insertion { at, unit: a },
        (false, true) => Edit::Deletion { at, unit: r },
        (false, false) if r.len() == a.len() => Edit::Substitution { at, len: r.len() },
        (false, false) => Edit::Complex { at, len: r.len() },
    }
}

/// Where the equivalent placements of an edit can sit, as found by [`ambiguity_span`].
#[derive(Debug, PartialEq, Eq)]
enum Placement {
    /// The edit claims fixed positions and needs no margin: substitutions.
    Fixed,
    /// Every placement spelling the same haplotype lies inside this interval, margins included.
    Within(Range<i64>),
    /// The repeat continues past [`MAX_INDEL_SLIDE`], so no finite span is placement-proof.
    Unbounded,
}

/// The reference interval containing every placement of `edit` that spells the same haplotype,
/// plus one margin base on each side.
///
/// The margins are what make the comparison placement-proof. [`read_seq_over_ref_span`] splices
/// in an insertion only when it sits *strictly* inside the span, so the left margin puts the
/// leftmost equivalent placement inside and the right margin does the same at the other end. A
/// read may then spell its indel anywhere in the repeat and still produce the same window.
fn ambiguity_span(edit: &Edit, reference: RefSlice) -> Placement {
    match *edit {
        Edit::Substitution { .. } => Placement::Fixed,
        // A complex allele can insert bases at either edge of the REF bases it replaces. Those
        // insertions sit on the boundary, so without a margin they would fall outside the span
        // and a read spelling the ALT would read back as REF.
        Edit::Complex { at, len } => {
            let Ok(len) = i64::try_from(len) else {
                return Placement::Unbounded;
            };
            Placement::Within(at - 1..at + len + 1)
        }
        Edit::Insertion { at, unit } => {
            let len = unit.len();
            if len == 0 {
                // Not produced by `classify`, but `% len` must never see it.
                return Placement::Fixed;
            }
            let unit_base = |i: usize| unit.get(i).map(u8::to_ascii_uppercase);
            // Sliding the anchor one base right rotates the inserted unit one base left, so the
            // unit base that has to match the reference walks forward with the anchor.
            let mut right = at;
            let mut cursor = 0;
            while reference
                .base(right)
                .is_some_and(|b| Some(b) == unit_base(cursor))
            {
                if right - at == MAX_INDEL_SLIDE {
                    return Placement::Unbounded;
                }
                right += 1;
                cursor = (cursor + 1) % len;
            }
            // Sliding left rotates the other way, so it walks backwards from the unit's end.
            let mut left = at;
            let mut cursor = len - 1;
            while reference
                .base(left - 1)
                .is_some_and(|b| Some(b) == unit_base(cursor))
            {
                if at - left == MAX_INDEL_SLIDE {
                    return Placement::Unbounded;
                }
                left -= 1;
                cursor = if cursor == 0 { len - 1 } else { cursor - 1 };
            }
            Placement::Within(left - 1..right + 1)
        }
        Edit::Deletion { at, unit } => {
            // Deleting `[q, q + len)` equals deleting `[q + 1, q + 1 + len)` exactly when the
            // base leaving the window equals the one entering it.
            let Ok(len) = i64::try_from(unit.len()) else {
                return Placement::Unbounded;
            };
            let mut right = at;
            while reference.same_base(right, right + len) {
                if right - at == MAX_INDEL_SLIDE {
                    return Placement::Unbounded;
                }
                right += 1;
            }
            let mut left = at;
            while reference.same_base(left - 1, left - 1 + len) {
                if at - left == MAX_INDEL_SLIDE {
                    return Placement::Unbounded;
                }
                left -= 1;
            }
            // The rightmost placement deletes up to `right + len`.
            Placement::Within(left - 1..right + len + 1)
        }
    }
}

/// The sequence each of a record's alleles predicts a read will spell over one common reference
/// span, so that a read is matched with a single window comparison rather than once per ALT.
struct AlleleWindows {
    /// Reference interval the read window is taken over: the record's REF span, widened to
    /// swallow the placement ambiguity of every length-changing ALT.
    span: Range<i64>,
    /// Expected sequence per allele index, `0` = REF.
    windows: Vec<Vec<u8>>,
}

impl AlleleWindows {
    /// `alleles` is `[REF, ALT1, ...]` as it appears in the record, at 0-based `pos`.
    ///
    /// `None` when an allele is symbolic (`<DEL>`, `*`, breakends), when no ALT differs from REF,
    /// when an indel sits in a repeat longer than [`MAX_INDEL_SLIDE`] allows to swallow,
    /// or when `reference` does not cover the span — none of those can be compared, and guessing
    /// is worse than abstaining.
    fn build(pos: i64, alleles: &[&[u8]], reference: RefSlice) -> Option<Self> {
        if alleles.len() < 2 || alleles.iter().any(|a| !is_plain_sequence(a)) {
            return None;
        }
        let (&ref_allele, alts) = alleles.split_first()?;
        let record_end = pos + i64::try_from(ref_allele.len()).ok()?;

        // A record whose alleles all have the REF's length claims each base at a fixed position,
        // so the span can shrink to the bases that actually differ. That keeps a read starting
        // inside a long MNV usable, and keeps an SNV's span one base wide so a neighbouring
        // variant's insertion has nowhere to leak in.
        if alleles.iter().all(|a| a.len() == ref_allele.len()) {
            let (mut lo, mut hi) = (record_end, pos);
            for alt in alts {
                if let Edit::Substitution { at, len } = classify(pos, ref_allele, alt)
                    && len > 0
                {
                    lo = lo.min(at);
                    hi = hi.max(at + i64::try_from(len).ok()?);
                }
            }
            if hi <= lo {
                return None; // every ALT equals REF: nothing to tell apart
            }
            let (from, to) = (
                usize::try_from(lo - pos).ok()?,
                usize::try_from(hi - pos).ok()?,
            );
            let windows = alleles
                .iter()
                .map(|allele| allele.get(from..to).map(<[u8]>::to_ascii_uppercase))
                .collect::<Option<_>>()?;
            return Some(Self {
                span: lo..hi,
                windows,
            });
        }

        // Otherwise at least one allele changes length. Widen the span to swallow every
        // equivalent placement, then let each allele fill the middle between reference flanks.
        let mut span = pos..record_end;
        for alt in alts {
            match ambiguity_span(&classify(pos, ref_allele, alt), reference) {
                Placement::Fixed => {}
                Placement::Within(widened) => {
                    span.start = span.start.min(widened.start);
                    span.end = span.end.max(widened.end);
                }
                Placement::Unbounded => return None,
            }
        }

        let left = reference.get(span.start..pos)?;
        let right = reference.get(record_end..span.end)?;
        let windows = alleles
            .iter()
            .map(|allele| {
                let mut w = Vec::with_capacity(left.len() + allele.len() + right.len());
                w.extend_from_slice(left);
                w.extend_from_slice(allele);
                w.extend_from_slice(right);
                w.make_ascii_uppercase();
                w
            })
            .collect();
        Some(Self { span, windows })
    }

    /// The allele index whose expected sequence is exactly `window`.
    ///
    /// `None` when nothing matches — the read carries some other allele, or an error, or a
    /// neighbouring variant inside the span — and also when two alleles predict the same
    /// sequence, where the read cannot tell them apart.
    fn index_of(&self, window: &[u8]) -> Option<u32> {
        let mut hit = None;
        for (i, expected) in self.windows.iter().enumerate() {
            if expected == window {
                if hit.is_some() {
                    return None;
                }
                #[allow(clippy::cast_possible_truncation)]
                {
                    hit = Some(i as u32);
                }
            }
        }
        hit
    }
}

/// Whether an allele is a plain nucleotide string, i.e. something a read can be compared to.
/// Rules out symbolic alleles (`<DEL>`), the spanning-deletion marker `*` and breakend syntax.
fn is_plain_sequence(allele: &[u8]) -> bool {
    !allele.is_empty()
        && allele
            .iter()
            .all(|b| matches!(b.to_ascii_uppercase(), b'A' | b'C' | b'G' | b'T' | b'N'))
}

/// Per-node metadata, precomputed once and indexed in lockstep with `node_indices`.
struct NodeInfo {
    /// GT allele indices of the two het slots (both present, distinct).
    slots: [u32; 2],
    /// Expected read sequence per allele. `None` when the record cannot be matched at all
    /// (symbolic allele, or reference not available across the span); such a node simply
    /// contributes no evidence.
    windows: Option<AlleleWindows>,
}

impl NodeInfo {
    /// Map the allele a read carries to a GT slot: `false` = slot 0, `true` = slot 1. `None` =
    /// the read carries neither slot allele (e.g. REF at a `1/2` site) or does not cover.
    ///
    /// `buf` is scratch space for the read's window, reused across reads and nodes.
    fn slot_label(&self, read: &bam::Record, min_base_qual: u8, buf: &mut Vec<u8>) -> Option<bool> {
        let windows = self.windows.as_ref()?;
        read_seq_over_ref_span(read, &windows.span, min_base_qual, buf)?;
        let idx = windows.index_of(buf)?;
        if idx == self.slots[0] {
            Some(false)
        } else if idx == self.slots[1] {
            Some(true)
        } else {
            None
        }
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub enum BamPhaseResolverError {
    MultiplePhaseSets(HashSet<i32>),
    BamReadError(rust_htslib::errors::Error),
    Other(anyhow::Error),
}

/// Attempt to resolve `UnphasedHet` records in `records` by read co-occurrence.
///
/// Reads covering the cluster `region` are fetched from `reader`. For each read the
/// supported allele (ALT or REF) at each record position is determined, and a
/// same/different evidence matrix is built. Records are assigned to haplotypes when
/// `settings.min_reads` reads support the dominant assignment AND at least
/// `settings.confidence` of informative reads agree.
///
/// Records that cannot be resolved remain `UnphasedHet` and will still block the cluster.
/// Records that are already `Phased` are used as anchors and are not changed.
pub fn resolve_phasing(
    records: &mut [Arc<InputRecord>],
    region: &GenomeRegion,
    reader: &mut bam::IndexedReader,
    settings: &PhasingSettings,
    reference: RefSlice<'_>,
) -> Result<Vec<Decision>, BamPhaseResolverError> {
    let unphased_indices: Vec<usize> = records
        .iter()
        .enumerate()
        .filter_map(|(i, rec)| {
            let gtp = rec.gt();
            // Records with a missing allele (e.g. `1/.`) carry no resolvable second slot.
            (gtp.is_unphased_het() && !gtp.has_missing()).then_some(i)
        })
        .collect();

    if unphased_indices.is_empty() {
        return Ok(vec![]);
    }

    // Collect anchors: phased het records with their index in `records` and GtAndPhase.
    // Hom records are excluded — they carry no directional (H0 vs H1) evidence.
    let anchors: Vec<(usize, GtAndPhase)> = records
        .iter()
        .enumerate()
        .filter_map(|(i, rec)| {
            let gtp = rec.gt();
            if gtp.phase.is_some() && !gtp.is_hom() {
                Some((i, gtp))
            } else {
                None
            }
        })
        .collect();

    // If anchors span multiple distinct PSs, skip phasing — too ambiguous.
    let distinct_ps: HashSet<i32> = anchors.iter().filter_map(|(_, ps)| ps.phase).collect();
    if distinct_ps.len() > 1 {
        return Err(BamPhaseResolverError::MultiplePhaseSets(distinct_ps));
    }

    // Build the ordered list of nodes participating in evidence (anchors first, then unresolved).
    // Each node_indices[k] is an index into `records`.
    let node_indices: Vec<usize> = anchors
        .iter()
        .map(|(i, _)| *i)
        .chain(unphased_indices.iter().copied())
        .collect();
    let anchor_count = anchors.len();

    // Precompute per-node metadata once (avoids re-parsing genotypes / re-allocating `alleles()`
    // for every read). All nodes are het with both slots present, so the lookups below cannot
    // fail; they are checked anyway to keep a malformed cluster from taking the run down.
    let node_info: Vec<NodeInfo> = node_indices
        .iter()
        .map(|&ri| {
            let rec = records
                .get(ri)
                .with_context(|| format!("Node index {ri} is out of the cluster's records"))?;
            let gtp = rec.gt();
            let [Some(slot_0), Some(slot_1)] = gtp.alleles else {
                bail!("Node at record index {ri} is not a het genotype with both slots present");
            };
            Ok(NodeInfo {
                slots: [slot_0, slot_1],
                windows: AlleleWindows::build(rec.pos(), &rec.alleles(), reference),
            })
        })
        .collect::<anyhow::Result<_>>()
        .map_err(BamPhaseResolverError::Other)?;

    let evidence = accumulate_evidence(reader, region, &node_info, settings)?;

    // Determine PS for resolved records.
    let (assigned_phaseset, has_anchors) =
        if let Some(ps) = anchors.first().and_then(|(_, gtp)| gtp.phase) {
            (ps, true)
        } else {
            // Without an anchor the cluster gets its own phase set, keyed on the first record.
            let ps = records
                .first()
                .map_or(0, |r| i32::try_from(r.pos() + 1).unwrap_or(i32::MAX));
            (ps, false)
        };

    let (assignment, decisions) = assign_orientations(
        &evidence,
        anchor_count,
        unphased_indices.len(),
        has_anchors,
        settings,
    );

    apply_assignments(
        records,
        &unphased_indices,
        &assignment,
        &node_info,
        anchor_count,
        assigned_phaseset,
    );

    Ok(decisions)
}

/// A symmetric `n × n` tally over the nodes, stored flat in row-major order: a lookup is one
/// bounds-checked offset instead of a bounds-checked row lookup plus a pointer chase into a
/// separate per-row allocation.
struct CoOccurrence {
    counts: Vec<i32>,
    n: usize,
}

impl CoOccurrence {
    fn new(n: usize) -> Self {
        Self {
            counts: vec![0; n.saturating_mul(n)],
            n,
        }
    }

    /// The number of nodes this matrix covers.
    const fn len(&self) -> usize {
        self.n
    }

    /// The tally for the node pair `(i, j)`. An out-of-range pair reads as `0`, i.e. as "these
    /// two nodes were never seen together", which can only ever withhold a phasing decision.
    fn get(&self, i: usize, j: usize) -> i32 {
        self.counts.get(i * self.n + j).copied().unwrap_or(0)
    }

    /// Count one read for the node pair `(i, j)`, in both directions.
    fn tally(&mut self, i: usize, j: usize) {
        for ix in [i * self.n + j, j * self.n + i] {
            if let Some(count) = self.counts.get_mut(ix) {
                *count = count.saturating_add(1);
            }
        }
    }
}

/// Symmetric co-occurrence matrices over the nodes, indexed in lockstep with `node_indices`.
struct Evidence {
    /// `same.get(i, j)`: read carries the same slot at both i and j.
    ///
    /// At two het sites REF/REF is as informative as ALT/ALT — it says the two REF alleles are in
    /// cis, hence so are the two ALTs. It was once excluded because REF is the matcher's fallback
    /// answer and false REFs were therefore common, but censoring only `same` and never `diff`
    /// biases every decision toward Flipped; the span comparison removes the false REFs at
    /// their source instead.
    same: CoOccurrence,
    /// `diff.get(i, j)`: read carries different slots at i and j.
    diff: CoOccurrence,
}

/// Scan the reads covering `region` and tally per-read slot agreement between every pair of nodes.
fn accumulate_evidence(
    reader: &mut bam::IndexedReader,
    region: &GenomeRegion,
    node_info: &[NodeInfo],
    settings: &PhasingSettings,
) -> Result<Evidence, BamPhaseResolverError> {
    let n = node_info.len();
    let mut same = CoOccurrence::new(n);
    let mut diff = CoOccurrence::new(n);

    let fd = match FetchDefinition::try_from(region) {
        Ok(fd) => fd,
        Err(e) => {
            warn!("local_phasing: cannot build fetch definition: {e}");
            return Err(BamPhaseResolverError::Other(e));
        }
    };
    if let Err(e) = reader.fetch(fd) {
        warn!("local_phasing: fetch failed: {e}");
        return Err(BamPhaseResolverError::BamReadError(e));
    }

    let mut bam_rec = bam::Record::new();
    // Reused across reads and nodes so the scan allocates nothing per read.
    let mut window = Vec::new();
    let mut support: Vec<Option<bool>> = vec![None; n];
    while let Some(result) = reader.read(&mut bam_rec) {
        if result.is_err() {
            warn!("local_phasing: BAM read error; stopping scan for this cluster");
            break;
        }

        if !settings.bam_filters.apply(&bam_rec) || bam_rec.mapq() < settings.min_mapq {
            continue;
        }

        // Per-node GT slot for this read; None = uninformative.
        for (slot, info) in support.iter_mut().zip(node_info) {
            *slot = info.slot_label(&bam_rec, settings.min_base_qual, &mut window);
        }

        for (i, label_i) in support.iter().enumerate() {
            let Some(si) = *label_i else { continue };
            for (j, label_j) in support.iter().enumerate().skip(i + 1) {
                let Some(sj) = *label_j else { continue };
                if si == sj {
                    same.tally(i, j);
                } else {
                    diff.tally(i, j);
                }
            }
        }
    }

    Ok(Evidence { same, diff })
}

/// Turn the co-occurrence evidence into a per-unresolved-record orientation, plus the decision
/// (including the reason for staying unresolved) that produced it.
///
/// Nodes `0..anchor_count` are the phased anchors, `anchor_count..` the unresolved records in
/// the order of `unphased_indices`.
fn assign_orientations(
    Evidence { same, diff }: &Evidence,
    anchor_count: usize,
    unresolved_count: usize,
    has_anchors: bool,
    settings: &PhasingSettings,
) -> (Vec<Option<Orientation>>, Vec<Decision>) {
    let n = same.len();
    let mut assignment: Vec<Option<Orientation>> = Vec::with_capacity(unresolved_count);

    // Pick the orientation whose vote total clears the min-reads and confidence gates.
    // `v_direct` favours keeping the node's GT slot order, `v_flipped` favours swapping it.
    let decide = |v_direct: i32, v_flipped: i32| -> Decision {
        let total = (v_direct + v_flipped).max(0).unsigned_abs();
        if total == 0 {
            return Decision::NoEvidence;
        }
        let (winner, winner_count) = if v_direct >= v_flipped {
            (Orientation::Direct, v_direct.max(0).unsigned_abs())
        } else {
            (Orientation::Flipped, v_flipped.max(0).unsigned_abs())
        };
        if winner_count < settings.min_reads {
            return Decision::InsufficientReads;
        }
        let fraction = f64::from(winner_count) / f64::from(total);
        if fraction < settings.confidence {
            return Decision::LowConfidence;
        }
        Decision::Resolved(winner)
    };

    let mut decisions = Vec::new();

    for k in 0..unresolved_count {
        let node_k = anchor_count + k;

        if has_anchors {
            // A phased anchor's slot 0 is H0 and slot 1 is H1 by definition, and node labels use
            // the same slot convention. So a read agreeing on labels (same) across anchor and node
            // supports the Direct orientation; a disagreement (diff) supports Flipped — regardless
            // of the anchor's genotype.
            let mut v_direct = 0i32;
            let mut v_flipped = 0i32;
            for a_node in 0..anchor_count {
                v_direct += same.get(a_node, node_k);
                v_flipped += diff.get(a_node, node_k);
            }
            assignment.push(record_outcome(decide(v_direct, v_flipped), &mut decisions));
        } else {
            // No anchors: greedy partition.
            if k == 0 {
                // Seed record: assign Direct only when co-read evidence meets min_reads.
                // Use the maximum pairwise co-coverage with any other node as the read count.
                let max_pair_cov: u32 = (0..n)
                    .filter(|&j| j != node_k)
                    .map(|j| {
                        (same.get(node_k, j) + diff.get(node_k, j))
                            .max(0)
                            .unsigned_abs()
                    })
                    .max()
                    .unwrap_or(0);
                let decision = if max_pair_cov == 0 {
                    Decision::NoEvidence
                } else if max_pair_cov < settings.min_reads {
                    Decision::InsufficientReads
                } else {
                    Decision::Resolved(Orientation::Direct)
                };
                assignment.push(record_outcome(decision, &mut decisions));
                continue;
            }
            let mut v_direct = 0i32;
            let mut v_flipped = 0i32;
            for (j, item) in assignment.iter().enumerate() {
                let node_j = anchor_count + j;
                match item {
                    Some(Orientation::Direct) => {
                        v_direct += same.get(node_j, node_k);
                        v_flipped += diff.get(node_j, node_k);
                    }
                    Some(Orientation::Flipped) => {
                        v_flipped += same.get(node_j, node_k);
                        v_direct += diff.get(node_j, node_k);
                    }
                    None => {}
                }
            }
            assignment.push(record_outcome(decide(v_direct, v_flipped), &mut decisions));
        }
    }

    (assignment, decisions)
}

/// Attach the resolved phased genotype and the cluster's phase set to the records that
/// local phasing could orient.
fn apply_assignments(
    records: &mut [Arc<InputRecord>],
    unphased_indices: &[usize],
    assignment: &[Option<Orientation>],
    node_info: &[NodeInfo],
    anchor_count: usize,
    assigned_phaseset: i32,
) {
    // Node k occupies position anchor_count + k in node_info, in lockstep with the k-th
    // unresolved record and the k-th assignment.
    let nodes = node_info.iter().skip(anchor_count);
    for ((&rec_idx, orientation), info) in unphased_indices.iter().zip(assignment).zip(nodes) {
        let Some(orientation) = orientation else {
            continue;
        };
        let [g0, g1] = info.slots;

        // Direct: g0 on H0, g1 on H1 → "g0|g1". Flipped: swap → "g1|g0".
        let (new_a0, new_a1): (u32, u32) = match orientation {
            Orientation::Direct => (g0, g1),
            Orientation::Flipped => (g1, g0),
        };

        let Some(record) = records.get_mut(rec_idx) else {
            error!("Cannot apply local phasing: record index {rec_idx} is out of range");
            continue;
        };

        // The genotype is attached to the record rather than written into it: the record is
        // bound to the input header, which may not declare GT or PS at all. The writer emits
        // both onto the output records it builds.
        *record = Arc::new(record.with_local_gt(GtAndPhase {
            alleles: [Some(new_a0), Some(new_a1)],
            phase: Some(assigned_phaseset),
        }));
    }
}

/// The sequence a read presents across the reference interval `span`, written into `out`.
///
/// Deleted reference positions contribute nothing and insertions inside the interval are
/// spliced in, so the result is the read's own sequence over that stretch of reference however
/// its CIGAR happens to spell the edits. Bases are upper-cased.
///
/// Insertions count only when they sit *strictly* inside the span (`start < ref_pos < end`). An
/// insertion at either edge belongs to the neighbouring reference position, not to this span.
/// Callers that need a record's own insertion caught give the span a margin base on each side
/// (see [`ambiguity_span`]); callers comparing a fixed-width allele do not, so a neighbouring
/// variant's insertion cannot leak in.
///
/// Returns `None` when the read does not cover the whole interval, when a base below
/// `min_base_qual` falls inside it, or when a reference skip makes the stretch incomparable.
/// `out` is cleared on entry and its contents are meaningless unless `Some` is returned.
fn read_seq_over_ref_span(
    read: &bam::Record,
    span: &Range<i64>,
    min_base_qual: u8,
    out: &mut Vec<u8>,
) -> Option<()> {
    use rust_htslib::bam::record::Cigar;

    let (start, end_excl) = (span.start, span.end);
    out.clear();
    if start >= end_excl || read.pos() > start {
        return None;
    }

    let seq = read.seq();
    let qual = read.qual();
    let mut ref_pos = read.pos();
    let mut query_pos: usize = 0;
    // How far into the interval the reference-consuming operations have accounted for.
    let mut covered_to = start;

    // Push query base `qi`, rejecting the whole span if it is missing or low-quality.
    let push = |out: &mut Vec<u8>, qi: usize| -> Option<()> {
        if qi >= seq.len() || qual.get(qi).is_some_and(|&q| q < min_base_qual) {
            return None;
        }
        out.push(seq[qi].to_ascii_uppercase());
        Some(())
    };

    for op in &read.cigar() {
        match op {
            Cigar::Match(raw_len) | Cigar::Equal(raw_len) | Cigar::Diff(raw_len) => {
                let op_len = i64::from(*raw_len);
                let lo = ref_pos.max(start);
                let hi = (ref_pos + op_len).min(end_excl);
                if hi > lo {
                    let first = query_pos + usize::try_from(lo - ref_pos).ok()?;
                    let count = usize::try_from(hi - lo).ok()?;
                    for qi in first..first + count {
                        push(out, qi)?;
                    }
                    covered_to = covered_to.max(hi);
                }
                ref_pos += op_len;
                query_pos += *raw_len as usize;
            }
            Cigar::Ins(raw_len) => {
                if ref_pos > start && ref_pos < end_excl {
                    for i in 0..*raw_len as usize {
                        push(out, query_pos + i)?;
                    }
                }
                query_pos += *raw_len as usize;
            }
            Cigar::Del(raw_len) => {
                let op_len = i64::from(*raw_len);
                let hi = (ref_pos + op_len).min(end_excl);
                if hi > ref_pos.max(start) {
                    covered_to = covered_to.max(hi);
                }
                ref_pos += op_len;
            }
            Cigar::RefSkip(raw_len) => {
                let op_len = i64::from(*raw_len);
                if ref_pos < end_excl && ref_pos + op_len > start {
                    return None; // a splice inside the span is not comparable
                }
                ref_pos += op_len;
            }
            Cigar::SoftClip(raw_len) => query_pos += *raw_len as usize,
            Cigar::HardClip(_) | Cigar::Pad(_) => {}
        }

        if ref_pos >= end_excl {
            break;
        }
    }

    (covered_to == end_excl).then_some(())
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use rust_htslib::bcf::record::GenotypeAllele;
    use rust_htslib::{
        bam::{self, record::CigarString},
        bcf::{self, Header, Writer},
    };

    use super::super::phasing::Haplotype;
    use super::*;
    use crate::common::{contig::ContigName, coords::GenomePosition};

    fn hap_of(gtp: &GtAndPhase) -> Option<Haplotype> {
        match gtp.alleles {
            [Some(a), _] if a > 0 => Some(Haplotype::H0),
            [Some(0), Some(b)] if b > 0 => Some(Haplotype::H1),
            _ => None,
        }
    }

    // ── helpers ───────────────────────────────────────────────────────────────

    fn make_vcf_header() -> Header {
        let mut h = Header::new();
        h.push_record(b"##contig=<ID=chr1,length=1000000>");
        h.push_record(b"##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">");
        h.push_record(b"##FORMAT=<ID=PS,Number=1,Type=Integer,Description=\"Phase set\">");
        h.push_sample(b"S1");
        h
    }

    fn make_unphased_het(writer: &Writer, pos: i64, ref_a: &[u8], alt_a: &[u8]) -> InputRecord {
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(&[ref_a, alt_a]).unwrap();
        rec.push_genotypes(&[GenotypeAllele::Unphased(0), GenotypeAllele::Unphased(1)])
            .unwrap();
        InputRecord::new(rec, 0)
    }

    fn make_phased_het(
        writer: &Writer,
        pos: i64,
        ref_a: &[u8],
        alt_a: &[u8],
        hap: Haplotype,
        ps: i32,
    ) -> InputRecord {
        let (a0, a1) = if hap == Haplotype::H1 {
            (GenotypeAllele::Unphased(0), GenotypeAllele::Phased(1))
        } else {
            (GenotypeAllele::Unphased(1), GenotypeAllele::Phased(0))
        };
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(&[ref_a, alt_a]).unwrap();
        rec.push_genotypes(&[a0, a1]).unwrap();
        rec.push_format_integer(b"PS", &[ps]).unwrap();
        InputRecord::new(rec, 0)
    }

    /// Build a phased het record for a tri-allelic (or larger) site.
    /// `alleles` = [REF, ALT1, ALT2, ...]; `gt` = (`pos0_idx`, `pos1_idx`) as GT allele indices.
    fn make_phased_het_multi(
        writer: &Writer,
        pos: i64,
        alleles: &[&[u8]],
        gt: (u32, u32),
        ps: i32,
    ) -> InputRecord {
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(alleles).unwrap();
        rec.push_genotypes(&[
            GenotypeAllele::Unphased(gt.0 as i32),
            GenotypeAllele::Phased(gt.1 as i32),
        ])
        .unwrap();
        rec.push_format_integer(b"PS", &[ps]).unwrap();
        InputRecord::new(rec, 0)
    }

    /// Build a minimal BAM record for CIGAR-based unit tests (no index needed). MAPQ 60 and
    /// uniform Phred-60 base qualities, so it passes the default MAPQ/base-quality gates.
    fn make_bam_record(pos: i64, seq: &[u8], cigar: &CigarString) -> bam::Record {
        make_bam_record_q(pos, seq, cigar, &vec![60u8; seq.len()])
    }

    /// Like [`make_bam_record`] but with explicit per-base qualities (Phred). MAPQ is 60.
    fn make_bam_record_q(pos: i64, seq: &[u8], cigar: &CigarString, quals: &[u8]) -> bam::Record {
        let mut rec = bam::Record::new();
        rec.set_pos(pos);
        rec.set_tid(0);
        rec.unset_unmapped();
        rec.set(b"read1", Some(cigar), seq, quals);
        rec.set_mapq(60);
        rec.cache_cigar();
        rec
    }

    fn make_bam_header() -> bam::Header {
        let mut header = bam::Header::new();
        let mut sq = bam::header::HeaderRecord::new(b"SQ");
        sq.push_tag(b"SN", "chr1");
        sq.push_tag(b"LN", 1_000_000i32);
        header.push_record(&sq);
        header
    }

    fn write_bam_and_index(mut records: Vec<bam::Record>, path: &std::path::Path) {
        let header = make_bam_header();
        let mut writer = bam::Writer::from_path(path, &header, bam::Format::Bam).unwrap();
        for rec in &mut records {
            rec.set_tid(0);
            writer.write(rec).unwrap();
        }
        drop(writer);
        bam::index::build(path, None, bam::index::Type::Bai, 1).unwrap();
    }

    fn make_indexed_reader(path: &std::path::Path) -> bam::IndexedReader {
        bam::IndexedReader::from_path(path).unwrap()
    }

    fn make_region(pos: usize, len: usize) -> GenomeRegion {
        GenomeRegion::new_bounded(GenomePosition::new_0(ContigName::new(b"chr1"), pos), len)
    }

    fn lenient_settings() -> PhasingSettings {
        PhasingSettings {
            min_reads: 1,
            confidence: 0.6,
            ..PhasingSettings::default()
        }
    }

    /// A 300 bp reference of `A`s, starting at position 0, with each `(pos, seq)` pasted in.
    /// Spelling out the local reference per test is the point: the comparison spans of indels
    /// are derived from it, so the flanks are part of the fixture, not background.
    fn reference_with(patches: &[(i64, &[u8])]) -> Vec<u8> {
        let mut reference = vec![b'A'; 300];
        for (pos, seq) in patches {
            let at = usize::try_from(*pos).unwrap();
            reference[at..at + seq.len()].copy_from_slice(seq);
        }
        reference
    }

    /// A reference carrying each record's REF allele at its own position. Enough for
    /// substitution-only clusters, whose comparison spans never leave their REF span.
    fn reference_for(records: &[Arc<InputRecord>]) -> Vec<u8> {
        let patches: Vec<(i64, Vec<u8>)> = records
            .iter()
            .map(|rec| (rec.pos(), rec.alleles()[0].to_vec()))
            .collect();
        reference_with(
            &patches
                .iter()
                .map(|(pos, seq)| (*pos, seq.as_slice()))
                .collect::<Vec<_>>(),
        )
    }

    /// Which allele index `read` carries at a record with `alleles` at `pos`, given `reference`
    /// starting at position 0.
    fn allele_index_of(
        reference: &[u8],
        read: &bam::Record,
        pos: i64,
        alleles: &[&[u8]],
        min_base_qual: u8,
    ) -> Option<u32> {
        let windows = AlleleWindows::build(pos, alleles, RefSlice::new(reference, 0))?;
        let mut buf = Vec::new();
        read_seq_over_ref_span(read, &windows.span, min_base_qual, &mut buf)?;
        windows.index_of(&buf)
    }

    /// Bi-allelic shorthand: `Some(true)` = ALT, `Some(false)` = REF, `None` = uninformative.
    fn allele_of(
        reference: &[u8],
        read: &bam::Record,
        pos: i64,
        ref_a: &[u8],
        alt_a: &[u8],
        min_base_qual: u8,
    ) -> Option<bool> {
        match allele_index_of(reference, read, pos, &[ref_a, alt_a], min_base_qual)? {
            0 => Some(false),
            1 => Some(true),
            _ => None,
        }
    }

    // ── allele matching: substitutions ────────────────────────────────────────

    #[test]
    fn test_allele_support_snv_alt() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(102, b"A")]);
        let rec = make_bam_record(100, b"TTTTT", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(allele_of(&reference, &rec, 102, b"A", b"T", 0), Some(true));
    }

    #[test]
    fn test_allele_support_snv_ref() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(102, b"A")]);
        let rec = make_bam_record(100, b"AAAAA", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(allele_of(&reference, &rec, 102, b"A", b"T", 0), Some(false));
    }

    #[test]
    fn test_allele_support_snv_no_cover() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(200, b"A")]);
        let rec = make_bam_record(100, b"AAAAA", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(allele_of(&reference, &rec, 200, b"A", b"T", 0), None);
    }

    #[test]
    fn test_allele_support_mnv_alt() {
        use rust_htslib::bam::record::Cigar;
        // MNV: REF=AT (positions 102-103), ALT=GC. Read: AA GC AA.
        let reference = reference_with(&[(102, b"AT")]);
        let rec = make_bam_record(100, b"AAGCAA", &CigarString(vec![Cigar::Match(6)]));
        assert_eq!(
            allele_of(&reference, &rec, 102, b"AT", b"GC", 0),
            Some(true)
        );
    }

    #[test]
    fn test_allele_support_mnv_ref() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(102, b"AT")]);
        let rec = make_bam_record(100, b"AAATAA", &CigarString(vec![Cigar::Match(6)]));
        assert_eq!(
            allele_of(&reference, &rec, 102, b"AT", b"GC", 0),
            Some(false)
        );
    }

    /// A same-length record's span shrinks to the bases that actually differ, so a read starting
    /// inside its REF span is still usable. `REF=AT ALT=AC` only claims position 101.
    #[test]
    fn test_allele_support_mnv_read_starts_inside_ref_span() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"AT")]);
        let alt = make_bam_record(101, b"CA", &CigarString(vec![Cigar::Match(2)]));
        assert_eq!(
            allele_of(&reference, &alt, 100, b"AT", b"AC", 0),
            Some(true)
        );
        let refr = make_bam_record(101, b"TA", &CigarString(vec![Cigar::Match(2)]));
        assert_eq!(
            allele_of(&reference, &refr, 100, b"AT", b"AC", 0),
            Some(false)
        );
    }

    /// An SNV's span stays exactly one base wide, so a neighbouring variant's insertion sits
    /// outside it and cannot turn a plain SNV read into a mismatch.
    #[test]
    fn test_allele_support_snv_with_neighbouring_insertion_still_called() {
        use rust_htslib::bam::record::Cigar;
        // SNV A>T at pos=102, plus a 1bp insertion immediately after it.
        let reference = reference_with(&[(102, b"A")]);
        let rec = make_bam_record(
            100,
            b"AATGAA",
            &CigarString(vec![Cigar::Match(3), Cigar::Ins(1), Cigar::Match(2)]),
        );
        assert_eq!(allele_of(&reference, &rec, 102, b"A", b"T", 0), Some(true));
    }

    #[test]
    fn test_allele_support_symbolic_allele_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(102, b"A")]);
        let rec = make_bam_record(100, b"AAAAA", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(allele_of(&reference, &rec, 102, b"A", b"<DEL>", 0), None);
        assert_eq!(allele_of(&reference, &rec, 102, b"A", b"*", 0), None);
    }

    // ── allele matching: length-changing alleles ──────────────────────────────

    #[test]
    fn test_allele_support_deletion_alt() {
        use rust_htslib::bam::record::Cigar;
        // VCF: REF=AT ALT=A at 100 → delete the T at 101. Read: 1M 1D 1M.
        let reference = reference_with(&[(100, b"AT")]);
        let rec = make_bam_record(
            100,
            b"AA",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(1)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"AT", b"A", 0), Some(true));
    }

    #[test]
    fn test_allele_support_deletion_ref() {
        use rust_htslib::bam::record::Cigar;
        // Read spells the span as the reference does — no deletion → REF allele.
        let reference = reference_with(&[(100, b"AT")]);
        let rec = make_bam_record(100, b"ATA", &CigarString(vec![Cigar::Match(3)]));
        assert_eq!(
            allele_of(&reference, &rec, 100, b"AT", b"A", 0),
            Some(false)
        );
    }

    #[test]
    fn test_allele_support_insertion_alt() {
        use rust_htslib::bam::record::Cigar;
        // VCF: REF=A ALT=AT at 100 → insert a T after 100. Read: 1M 1I 1M.
        let reference = reference_with(&[(100, b"AC")]);
        let rec = make_bam_record(
            100,
            b"ATC",
            &CigarString(vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"A", b"AT", 0), Some(true));
    }

    #[test]
    fn test_allele_support_insertion_ref() {
        use rust_htslib::bam::record::Cigar;
        // Read has no insertion → REF allele.
        let reference = reference_with(&[(100, b"AC")]);
        let rec = make_bam_record(100, b"AC", &CigarString(vec![Cigar::Match(2)]));
        assert_eq!(
            allele_of(&reference, &rec, 100, b"A", b"AT", 0),
            Some(false)
        );
    }

    #[test]
    fn test_allele_support_insertion_foreign_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        // The read inserts G where the record's ALT inserts T → neither allele.
        let reference = reference_with(&[(100, b"AC")]);
        let rec = make_bam_record(
            100,
            b"AGC",
            &CigarString(vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"A", b"AT", 0), None);
    }

    /// The third-allele gap: at a 3bp deletion record the read carries a *1bp* deletion inside
    /// the REF span. Asked pointwise the read sat in a Match op and answered REF; over the span
    /// it spells neither allele, which is the honest answer. `chr1:212925722` scaled down.
    #[test]
    fn test_allele_support_deletion_third_allele_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTC")]);
        let rec = make_bam_record(
            100,
            b"AGGC",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(3)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"ATTT", b"A", 0), None);
    }

    #[test]
    fn test_allele_support_deletion_exact_is_alt() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTC")]);
        let rec = make_bam_record(
            100,
            b"AC",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(3), Cigar::Match(1)]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ATTT", b"A", 0),
            Some(true)
        );
    }

    #[test]
    fn test_allele_support_deletion_no_indel_is_ref() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTC")]);
        let rec = make_bam_record(100, b"ATTTC", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ATTT", b"A", 0),
            Some(false)
        );
    }

    /// The cost of comparing over a span: a read that stops inside it confirms nothing there.
    /// The reference allele of a stretch you have not seen is not something to assert.
    #[test]
    fn test_allele_support_deletion_partial_coverage_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTTTTTTTC")]);
        // REF=ATTTTTTTTT (10bp) ALT=A at 100; this read covers only 100-104.
        let short = make_bam_record(100, b"ATTTT", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(
            allele_of(&reference, &short, 100, b"ATTTTTTTTT", b"A", 0),
            None
        );
        // Likewise a read starting after the span begins, even right after the anchor base.
        let late = make_bam_record(101, b"TTTTTTTTTC", &CigarString(vec![Cigar::Match(10)]));
        assert_eq!(
            allele_of(&reference, &late, 100, b"ATTTTTTTTT", b"A", 0),
            None
        );
    }

    // ── allele matching: repeat-widened spans ─────────────────────────────────

    /// The span of an indel covers the whole repeat it could have been placed in, so a read
    /// spelling its insertion further into the homopolymer than the VCF does still matches ALT.
    /// Without the widening this read comes back as a false REF — the failure mode behind
    /// `chr1:212925716-212925734`.
    #[test]
    fn test_allele_support_insertion_shifted_in_homopolymer_is_alt() {
        use rust_htslib::bam::record::Cigar;
        // Reference A TTTT C at 100..105; VCF pos=100 REF=A ALT=AT (left-aligned).
        let reference = reference_with(&[(100, b"ATTTTC")]);
        // The aligner placed the extra T after reference position 102 instead.
        let rec = make_bam_record(
            100,
            b"ATTTTTC",
            &CigarString(vec![Cigar::Match(3), Cigar::Ins(1), Cigar::Match(3)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"A", b"AT", 0), Some(true));
        // A read without the extra T is REF, wherever the repeat is read from.
        let refr = make_bam_record(100, b"ATTTTC", &CigarString(vec![Cigar::Match(6)]));
        assert_eq!(
            allele_of(&reference, &refr, 100, b"A", b"AT", 0),
            Some(false)
        );
    }

    /// Same for deletions: the read deletes a T further right than the record spells it.
    #[test]
    fn test_allele_support_deletion_shifted_in_homopolymer_is_alt() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTTC")]);
        // VCF pos=100 REF=AT ALT=A deletes the T at 101; this read deletes the one at 103.
        let rec = make_bam_record(
            100,
            b"ATTTC",
            &CigarString(vec![Cigar::Match(3), Cigar::Del(1), Cigar::Match(2)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"AT", b"A", 0), Some(true));
    }

    /// A dinucleotide repeat: the unit rotates as the insertion slides, so the widening has to
    /// follow the period rather than a single base.
    #[test]
    fn test_allele_support_insertion_shifted_in_dinucleotide_repeat() {
        use rust_htslib::bam::record::Cigar;
        // Reference C ATATAT G at 100..108; VCF pos=100 REF=C ALT=CAT.
        let reference = reference_with(&[(100, b"CATATATG")]);
        // The read spells the extra AT four bases further right.
        let rec = make_bam_record(
            100,
            b"CATATATATG",
            &CigarString(vec![Cigar::Match(5), Cigar::Ins(2), Cigar::Match(3)]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"C", b"CAT", 0),
            Some(true)
        );
    }

    /// Widening stops where the repeat does: an insertion of a different unit right next to the
    /// record is a different allele, not a shifted one.
    #[test]
    fn test_allele_support_insertion_foreign_unit_in_repeat_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ATTTTC")]);
        let rec = make_bam_record(
            100,
            b"ATTGTTC",
            &CigarString(vec![Cigar::Match(3), Cigar::Ins(1), Cigar::Match(3)]),
        );
        assert_eq!(allele_of(&reference, &rec, 100, b"A", b"AT", 0), None);
    }

    /// A repeat longer than `MAX_INDEL_SLIDE` on either side cannot be fully swallowed by the
    /// span, so a read may spell the deletion outside it and then read back as the reference
    /// allele. Such a record must be uninformative rather than produce a false REF.
    #[test]
    fn test_allele_support_deletion_in_overlong_repeat_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        // 300bp poly-A; VCF deletes one A at 151. The read deletes one A at 20 instead —
        // equivalent, but 130bp away and so outside any capped span.
        let reference = reference_with(&[]);
        let rec = make_bam_record(
            0,
            &[b'A'; 299],
            &CigarString(vec![Cigar::Match(20), Cigar::Del(1), Cigar::Match(279)]),
        );
        assert_eq!(allele_of(&reference, &rec, 150, b"AA", b"A", 0), None);
        // A read without any deletion must not be called REF either: in an unbounded repeat
        // its window cannot rule out the deletion sitting just outside the span.
        let plain = make_bam_record(0, &[b'A'; 300], &CigarString(vec![Cigar::Match(300)]));
        assert_eq!(allele_of(&reference, &plain, 150, b"AA", b"A", 0), None);
    }

    /// Same for an insertion: the slide is capped, so the record abstains.
    #[test]
    fn test_allele_support_insertion_in_overlong_repeat_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[]);
        let rec = make_bam_record(
            0,
            &[b'A'; 301],
            &CigarString(vec![Cigar::Match(20), Cigar::Ins(1), Cigar::Match(280)]),
        );
        assert_eq!(allele_of(&reference, &rec, 150, b"A", b"AA", 0), None);
    }

    // ── allele matching: complex alleles ──────────────────────────────────────

    /// A complex allele whose ALT inserts bases at both edges of its REF span. The read
    /// spells exactly that ALT, but with insertions sitting on the span's boundaries; without
    /// a margin base they fall outside the window and the read reads back as REF.
    #[test]
    fn test_allele_support_complex_edge_insertions_are_alt() {
        use rust_htslib::bam::record::Cigar;
        // REF=AC ALT=GACG at 100: G inserted before 100 and after 101.
        let reference = reference_with(&[(100, b"AC")]);
        let rec = make_bam_record(
            98,
            b"AAGACGAA",
            &CigarString(vec![
                Cigar::Match(2),
                Cigar::Ins(1),
                Cigar::Match(2),
                Cigar::Ins(1),
                Cigar::Match(2),
            ]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"AC", b"GACG", 0),
            Some(true)
        );
    }

    /// A complex allele has no positional correspondence between allele characters and read
    /// bases, so it is compared as a sequence over the record's own REF span plus a margin base
    /// on each side. REF=ACCCGGCTAAT ALT=GCCCGGCTAA at 100 is an A>G substitution plus a 1bp deletion ten
    /// bases later; the read spells it as 10M 1D.
    #[test]
    fn test_allele_support_complex_alt() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        // The read covers one reference base on either side: the span's margins.
        let rec = make_bam_record(
            99,
            b"AGCCCGGCTAAAAAAA",
            &CigarString(vec![Cigar::Match(11), Cigar::Del(1), Cigar::Match(5)]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            Some(true)
        );
    }

    #[test]
    fn test_allele_support_complex_ref() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        let rec = make_bam_record(
            99,
            b"AACCCGGCTAATAAAAA",
            &CigarString(vec![Cigar::Match(17)]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            Some(false)
        );
    }

    /// The same molecule spelled with Equal/Diff instead of Match must give the same answer —
    /// the comparison is on sequence, not on how the aligner wrote the CIGAR.
    #[test]
    fn test_allele_support_complex_alt_alternative_cigar() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        let rec = make_bam_record(
            99,
            b"AGCCCGGCTAAAAAAA",
            &CigarString(vec![
                Cigar::Equal(1),
                Cigar::Diff(1),
                Cigar::Equal(9),
                Cigar::Del(1),
                Cigar::Equal(5),
            ]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            Some(true)
        );
    }

    #[test]
    fn test_allele_support_complex_read_does_not_span() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        // Read ends inside the REF span → nothing to compare.
        let rec = make_bam_record(100, b"ACCCG", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            None
        );
        // Read starts after the span begins → likewise.
        let late = make_bam_record(105, b"GCTAATTTTT", &CigarString(vec![Cigar::Match(10)]));
        assert_eq!(
            allele_of(&reference, &late, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            None
        );
    }

    #[test]
    fn test_allele_support_complex_low_base_quality() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        let mut quals = vec![60u8; 16];
        quals[3] = 5; // inside the REF span
        let rec = make_bam_record_q(
            100,
            b"ACCCGGCTAATTTTTT",
            &CigarString(vec![Cigar::Match(16)]),
            &quals,
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 20),
            None
        );
    }

    #[test]
    fn test_allele_support_complex_ref_skip_in_span() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"ACCCGGCTAAT")]);
        // A splice inside the span makes the stretch non-comparable.
        let rec = make_bam_record(
            100,
            b"ACCCGGCTAATTT",
            &CigarString(vec![Cigar::Match(5), Cigar::RefSkip(3), Cigar::Match(8)]),
        );
        assert_eq!(
            allele_of(&reference, &rec, 100, b"ACCCGGCTAAT", b"GCCCGGCTAA", 0),
            None
        );
    }

    // ── multi-allelic sites ───────────────────────────────────────────────────

    /// Regression: at `CTTT -> C,CTTTT` a read carrying ALT2 used to be called REF — ALT2
    /// returned `None` and was ignored while ALT1 ("read lacks this deletion") set `ref_seen`.
    /// One window compared against all alleles cannot make that mistake.
    #[test]
    fn test_index_multiallelic_insertion_alt_not_called_ref() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"CTTTA")]);
        let rec = make_bam_record(
            100,
            b"CTTTTAAAAA",
            &CigarString(vec![Cigar::Match(4), Cigar::Ins(1), Cigar::Match(5)]),
        );
        let alleles: [&[u8]; 3] = [b"CTTT", b"C", b"CTTTT"];
        assert_eq!(
            allele_index_of(&reference, &rec, 100, &alleles, 0),
            Some(2),
            "read carries ALT2, must not be reported as REF"
        );
    }

    /// A read carrying neither listed ALT is uninformative, never REF by elimination.
    #[test]
    fn test_index_multiallelic_foreign_insertion_is_uninformative() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"CTTTA")]);
        let rec = make_bam_record(
            100,
            b"CTTTGGAAAAA",
            &CigarString(vec![Cigar::Match(4), Cigar::Ins(2), Cigar::Match(5)]),
        );
        let alleles: [&[u8]; 3] = [b"CTTT", b"C", b"CTTTT"];
        assert_eq!(allele_index_of(&reference, &rec, 100, &alleles, 0), None);
    }

    /// The deletion ALT of the same site, read off the same single window.
    #[test]
    fn test_index_multiallelic_deletion_alt() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(100, b"CTTTA")]);
        let rec = make_bam_record(
            100,
            b"CAAAAA",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(3), Cigar::Match(5)]),
        );
        let alleles: [&[u8]; 3] = [b"CTTT", b"C", b"CTTTT"];
        assert_eq!(allele_index_of(&reference, &rec, 100, &alleles, 0), Some(1));
    }

    // ── resolve_phasing unit tests ────────────────────────────────────────────

    #[test]
    fn test_resolve_no_unphased_het() {
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &PhasingSettings::default(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        assert_eq!(input.len(), 1);
        // Anchor record: already phased, should be unchanged.
        let gtp = input[0].gt();
        assert!(gtp.phase.is_some(), "anchor should remain phased");
        assert_eq!(hap_of(&gtp), Some(Haplotype::H1));
    }

    #[test]
    fn test_resolve_two_unphased_hets_no_coverage() {
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let before = counter!("phasing.records.unresolved.no_evidence").get();
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &PhasingSettings::default(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        assert!(input[0].gt().is_unphased_het());
        assert!(input[1].gt().is_unphased_het());
        // Both records lack covering reads → both counted as no_evidence.
        assert_eq!(
            counter!("phasing.records.unresolved.no_evidence").get() - before,
            2
        );
    }

    #[test]
    fn test_resolve_two_unphased_hets_same_hap() {
        use rust_htslib::bam::record::Cigar;
        // r1 at pos=100 REF=A ALT=T, r2 at pos=110 REF=G ALT=C.
        // Two reads covering both positions: T at 100 AND C at 110 → same hap.
        let mut seq = vec![b'T'];
        seq.extend(b"AAAAAAAAA"); // positions 101-109
        seq.push(b'C'); // position 110
        seq.extend(b"AAAAAAAAA"); // positions 111-119
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let read1 = make_bam_record(100, &seq, &cigar);
        let read2 = make_bam_record(100, &seq, &cigar);

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![read1, read2], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let before = counter!("phasing.records.resolved").get();
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp0 = input[0].gt();
        let gtp1 = input[1].gt();
        assert!(gtp0.phase.is_some(), "r1 should be resolved");
        assert!(gtp1.phase.is_some(), "r2 should be resolved");
        assert_eq!(
            hap_of(&gtp0),
            hap_of(&gtp1),
            "both records should be on the same haplotype"
        );
        // Seed + dependent record both resolved.
        assert_eq!(counter!("phasing.records.resolved").get() - before, 2);
    }

    #[test]
    fn test_resolve_two_unphased_hets_opposite_haps() {
        use rust_htslib::bam::record::Cigar;
        // r1 at 100 REF=A ALT=T, r2 at 110 REF=G ALT=C.
        // hap0-reads: T at 100, G (ref) at 110.
        // hap1-reads: A (ref) at 100, C at 110.
        let mut s0 = vec![b'T'];
        s0.extend(b"AAAAAAAAA");
        s0.push(b'G'); // ref at 110
        s0.extend(b"AAAAAAAAA");

        let mut s1 = vec![b'A']; // ref at 100
        s1.extend(b"AAAAAAAAA");
        s1.push(b'C'); // alt at 110
        s1.extend(b"AAAAAAAAA");

        let cigar = CigarString(vec![Cigar::Match(20)]);
        let reads = vec![
            make_bam_record(100, &s0, &cigar),
            make_bam_record(100, &s0, &cigar),
            make_bam_record(100, &s1, &cigar),
            make_bam_record(100, &s1, &cigar),
        ];

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp0 = input[0].gt();
        let gtp1 = input[1].gt();
        assert!(
            gtp0.phase.is_some() && gtp1.phase.is_some(),
            "both should be resolved"
        );
        assert_ne!(
            hap_of(&gtp0),
            hap_of(&gtp1),
            "records should be on opposite haplotypes"
        );
    }

    #[test]
    fn test_resolve_below_min_reads_threshold() {
        use rust_htslib::bam::record::Cigar;
        // Only 1 read; min_reads=3 → the second record should remain UnphasedHet.
        let mut seq = vec![b'T'];
        seq.extend(b"AAAAAAAAA");
        seq.push(b'C');
        seq.extend(b"AAAAAAAAA");
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let read1 = make_bam_record(100, &seq, &cigar);

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![read1], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let settings = PhasingSettings {
            min_reads: 3,
            confidence: 0.0,
            ..PhasingSettings::default()
        };
        let before = counter!("phasing.records.unresolved.insufficient_reads").get();
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &settings,
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        // Seed has 1 covering read < min_reads=3 → insufficient_reads.
        assert_eq!(
            counter!("phasing.records.unresolved.insufficient_reads").get() - before,
            1
        );
        assert!(
            input[1].gt().is_unphased_het(),
            "second record should remain unphased with only 1 read < min_reads=3"
        );
        assert!(
            input[0].gt().is_unphased_het(),
            "seed (first) record should also remain unphased: 1 read < min_reads=3"
        );
    }

    #[test]
    fn test_resolve_below_confidence_threshold() {
        use rust_htslib::bam::record::Cigar;
        // 2 same-hap reads + 2 diff-hap reads → 50% confidence < 0.8 → second stays unphased.
        let mut s_same = vec![b'T'];
        s_same.extend(b"AAAAAAAAA");
        s_same.push(b'C');
        s_same.extend(b"AAAAAAAAA");

        let mut s_diff = vec![b'T'];
        s_diff.extend(b"AAAAAAAAA");
        s_diff.push(b'G'); // ref at 110
        s_diff.extend(b"AAAAAAAAA");

        let cigar = CigarString(vec![Cigar::Match(20)]);
        let reads = vec![
            make_bam_record(100, &s_same, &cigar),
            make_bam_record(100, &s_same, &cigar),
            make_bam_record(100, &s_diff, &cigar),
            make_bam_record(100, &s_diff, &cigar),
        ];

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let settings = PhasingSettings {
            min_reads: 1,
            confidence: 0.8,
            ..PhasingSettings::default()
        };
        let before = counter!("phasing.records.unresolved.low_confidence").get();
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &settings,
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        // 50% agreement < 0.8 confidence → low_confidence.
        assert_eq!(
            counter!("phasing.records.unresolved.low_confidence").get() - before,
            1
        );
        assert!(
            input[1].gt().is_unphased_het(),
            "second record should remain unphased below confidence threshold (50% < 0.8)"
        );
    }

    #[test]
    fn test_resolve_unphased_with_phased_anchor() {
        use rust_htslib::bam::record::Cigar;
        // r1 (pos=100): UnphasedHet, REF=A ALT=T.
        // r2 (pos=110): Phased H1, phaseset=100 (anchor).
        // Reads carry both ALTs → UnphasedHet should resolve to H1.
        let mut seq = vec![b'T']; // ALT at pos 100
        seq.extend(b"AAAAAAAAA");
        seq.push(b'C'); // ALT at pos 110
        seq.extend(b"AAAAAAAAA");
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let read1 = make_bam_record(100, &seq, &cigar);
        let read2 = make_bam_record(100, &seq, &cigar);

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het(&w, 100, b"A", b"T");
        let r2 = make_phased_het(&w, 110, b"G", b"C", Haplotype::H1, 100);
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![read1, read2], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp0 = input[0].gt();
        assert!(gtp0.phase.is_some(), "UnphasedHet should be resolved");
        assert_eq!(
            hap_of(&gtp0),
            Some(Haplotype::H1),
            "should resolve to same hap as anchor"
        );
        // Anchor (r2) unchanged:
        let gtp1 = input[1].gt();
        assert!(gtp1.phase.is_some(), "anchor should remain phased");
        assert_eq!(hap_of(&gtp1), Some(Haplotype::H1));
    }

    /// REF/REF is directional evidence like any other: at two het sites it says both REF alleles
    /// are in cis, hence both ALTs are too. The reads here are REF at both positions, so the
    /// record's REF joins the anchor's REF on H0 and its ALT lands on H1.
    #[test]
    fn test_resolve_refref_reads_are_evidence() {
        use rust_htslib::bam::record::Cigar;
        // Anchor 0|1@100 (ALT on H1), unphased 0/1@110. Every read is REF at both.
        let mut seq = vec![b'A']; // pos100 REF
        seq.extend(b"AAAAAAAAA"); // 101..109
        seq.push(b'G'); // pos110 REF
        seq.extend(b"AAAAAAAAA"); // 111..119
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let reads: Vec<bam::Record> = (0..5).map(|_| make_bam_record(100, &seq, &cigar)).collect();

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let unphased = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unphased)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(
            gtp.phase.is_some(),
            "REF/REF linkage must resolve the record"
        );
        assert_eq!(hap_of(&gtp), Some(Haplotype::H1));
    }

    #[test]
    fn test_resolve_low_mapq_reads_ignored() {
        use rust_htslib::bam::record::Cigar;
        // Anchor 0|1@100 (H1), unphased 0/1@110. Reads carry genuine ALT/ALT linkage that would
        // resolve the record, but all have MAPQ 5 (< default 20). Mis-mappable reads must not
        // count, so the record stays unphased.
        let mut seq = vec![b'T']; // ALT@100
        seq.extend(b"AAAAAAAAA");
        seq.push(b'C'); // ALT@110
        seq.extend(b"AAAAAAAAA");
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let reads: Vec<bam::Record> = (0..5)
            .map(|_| {
                let mut r = make_bam_record(100, &seq, &cigar);
                r.set_mapq(5);
                r
            })
            .collect();

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let unphased = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unphased)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        // Default settings → min_mapq=20. lenient_settings keeps min_mapq=20 via ..default too,
        // so use it for the lenient min_reads/confidence but the MAPQ gate still applies.
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        assert!(
            input[1].gt().is_unphased_het(),
            "reads below the MAPQ floor must not phase the record"
        );
    }

    #[test]
    fn test_resolve_low_base_quality_at_variant_ignored() {
        use rust_htslib::bam::record::Cigar;
        // Anchor 0|1@100 (H1), unphased 0/1@110. Reads carry ALT/ALT linkage, but the base AT the
        // unphased variant (pos 110, query index 10) has Phred 5 (< default 20). That call is
        // uninformative, so no evidence reaches the node and it stays unphased. The anchor base
        // (index 0) stays high-quality.
        let mut seq = vec![b'T']; // ALT@100
        seq.extend(b"AAAAAAAAA");
        seq.push(b'C'); // ALT@110
        seq.extend(b"AAAAAAAAA");
        let cigar = CigarString(vec![Cigar::Match(20)]);
        let mut quals = vec![60u8; seq.len()];
        quals[10] = 5; // low quality at pos 110
        let reads: Vec<bam::Record> = (0..5)
            .map(|_| make_bam_record_q(100, &seq, &cigar, &quals))
            .collect();

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let unphased = make_unphased_het(&w, 110, b"G", b"C");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unphased)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        // min_base_qual default is 20; lenient_settings keeps it via ..default.
        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        assert!(
            input[1].gt().is_unphased_het(),
            "a low-quality base at the variant must not phase the record"
        );
    }

    #[test]
    fn test_resolve_multiple_phaseset_early_exit() {
        // Two phased records with different PSs → ambiguous → return unchanged immediately.
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let r2 = make_phased_het(&w, 110, b"G", b"C", Haplotype::H0, 200); // different PS
        let r3 = make_unphased_het(&w, 120, b"C", b"G");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2), Arc::new(r3)];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 70);

        let reference = reference_for(&input);
        let err = resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &PhasingSettings::default(),
            RefSlice::new(&reference, 0),
        )
        .unwrap_err();
        assert!(
            matches!(err, BamPhaseResolverError::MultiplePhaseSets(_)),
            "anchors spanning two distinct phasesets should be rejected"
        );
        assert!(
            input[2].gt().is_unphased_het(),
            "multiple PSs should cause early exit leaving UnphasedHet unchanged"
        );
    }

    #[test]
    fn test_resolve_2_1_anchor_correct_direction() {
        use rust_htslib::bam::record::Cigar;
        // Anchor: 2|1 at pos=100, alleles=[A, T, C], GT=(2,1) → H0=C(ALT2), H1=T(ALT1).
        // read_allele_at_pos uses alleles[0]=A and alleles[1]=T, so ALT1=T reads are visible
        // (Some(true)=H1). With the old `> 0` formula anchor_is_h0=true and ALT1 reads would
        // be credited to H0 — inverted. With `== Some(1)` anchor_is_h0=false → H1. ✓
        //
        // Unresolved: 0/1 at pos=110, REF=G, ALT=A.
        // Reads: 3 reads carrying T at pos=100 (ALT1=H1 of anchor) and A at pos=110.
        // Expected: unresolved resolves to H1.

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het_multi(&w, 100, &[b"A", b"T", b"C"], (2, 1), 100);
        let unresolved = make_unphased_het(&w, 110, b"G", b"A");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unresolved)];

        // seq[0]=T → ref-pos 100 (ALT1 of 2|1 anchor), seq[10]=A → ref-pos 110 (ALT of unresolved).
        let mut seq = vec![b'T'];
        seq.extend(b"AAAAAAAAA"); // pos 101..109
        seq.push(b'A'); // pos 110 = ALT of unresolved (ALT=A, REF=G, so A≠G confirms alt)
        let cigar = CigarString(vec![Cigar::Match(seq.len() as u32)]);
        let reads: Vec<bam::Record> = (0..3).map(|_| make_bam_record(100, &seq, &cigar)).collect();

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(gtp.phase.is_some(), "unresolved should be phased");
        assert_eq!(
            hap_of(&gtp),
            Some(Haplotype::H1),
            "should be H1: ALT1 of 2|1 anchor is on H1"
        );
    }

    #[test]
    fn test_resolve_1_2_anchor_h0_evidence_correct() {
        use rust_htslib::bam::record::Cigar;
        // Anchor: 1|2 at pos=100, alleles=[A, T, C], GT=(1,2) → H0=T(ALT1), H1=C(ALT2).
        // ALT1=T reads are visible (Some(true)=H0). ALT2=C reads return None (invisible).
        // Unresolved: 0/1 at pos=110, REF=G, ALT=A.
        // Reads: 3 reads carrying T at pos=100 (H0) and A at pos=110.
        // Expected: unresolved resolves to H0.

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het_multi(&w, 100, &[b"A", b"T", b"C"], (1, 2), 100);
        let unresolved = make_unphased_het(&w, 110, b"G", b"A");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unresolved)];

        // seq[0]=T → ref-pos 100 (ALT1 of 1|2 anchor = H0), seq[10]=A → ref-pos 110.
        let mut seq = vec![b'T'];
        seq.extend(b"AAAAAAAAA"); // pos 101..109
        seq.push(b'A'); // pos 110 = ALT of unresolved (REF=G, ALT=A)
        let cigar = CigarString(vec![Cigar::Match(seq.len() as u32)]);
        let reads: Vec<bam::Record> = (0..3).map(|_| make_bam_record(100, &seq, &cigar)).collect();

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(gtp.phase.is_some(), "unresolved should be phased");
        assert_eq!(
            hap_of(&gtp),
            Some(Haplotype::H0),
            "should be H0: ALT1 of 1|2 anchor is on H0"
        );
    }

    #[test]
    fn test_resolve_missing_allele_not_modified() {
        // 1/. record: is_unphased_het()=true but has_missing()=true.
        // With the has_missing guard it must be excluded from unphased_indices and
        // left completely unchanged (no PS field, no modified GT).
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();

        let mut rec_missing = w.empty_record();
        let rid = rec_missing.header().name2rid(b"chr1").unwrap();
        rec_missing.set_rid(Some(rid));
        rec_missing.set_pos(100);
        rec_missing.set_alleles(&[b"A", b"T"]).unwrap();
        rec_missing
            .push_genotypes(&[GenotypeAllele::Unphased(1), GenotypeAllele::UnphasedMissing])
            .unwrap();

        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(InputRecord::new(rec_missing, 0))];

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(vec![], &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 30);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[0].gt();
        // has_missing → excluded from resolution → no PS written → still not phased
        assert!(
            !gtp.is_phased(),
            "1/. record must not be phased by resolve_phasing"
        );
        assert!(
            gtp.has_missing(),
            "alleles must remain unchanged (still has missing)"
        );
    }

    #[test]
    fn test_resolve_1_2_unphased_ref_reads_excluded() {
        use rust_htslib::bam::record::Cigar;
        // Anchor: 0|1 at pos=100, REF=A, ALT=T → H0=REF, H1=ALT.
        // Unresolved: 1/2 at pos=110, alleles=[G, C, A].
        //   Both GT allele indices > 0 → REF reads at this node must be excluded (Some(false)→None).
        //
        // Reads: 3 reads carry T at pos=100 (anchor H1=ALT) AND C at pos=110 (ALT1 of 1/2).
        //   → These should accumulate evidence toward H1 for the 1/2 node.
        // Noise reads: 3 reads carry T at pos=100 AND G (REF) at pos=110.
        //   → With the fix, REF at the 1/2 node returns None → not counted.
        //   → Without the fix, they would inflate diff and potentially prevent resolution.
        //
        // Expected: 1/2 node resolves to H1 (ALT1=C on H1 → written as 2|1).

        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);

        let mut rec_12 = w.empty_record();
        let rid = rec_12.header().name2rid(b"chr1").unwrap();
        rec_12.set_rid(Some(rid));
        rec_12.set_pos(110);
        rec_12.set_alleles(&[b"G", b"C", b"A"]).unwrap();
        rec_12
            .push_genotypes(&[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(2)])
            .unwrap();
        let mut input: Vec<Arc<InputRecord>> =
            vec![Arc::new(anchor), Arc::new(InputRecord::new(rec_12, 0))];

        // Signal reads: seq[0]=T (ALT=H1 of anchor), seq[10]=C (ALT1 of 1/2).
        let mut sig_seq = vec![b'T'];
        sig_seq.extend(b"AAAAAAAAA"); // pos 101..109
        sig_seq.push(b'C'); // pos 110 = ALT1 of 1/2
        let cigar = CigarString(vec![Cigar::Match(sig_seq.len() as u32)]);
        let mut reads: Vec<bam::Record> = (0..3)
            .map(|_| make_bam_record(100, &sig_seq, &cigar))
            .collect();

        // Noise reads: T at 100, G=REF at 110. REF at 1/2 node must be filtered (Some(false)→None).
        let mut noise_seq = vec![b'T'];
        noise_seq.extend(b"AAAAAAAAA"); // pos 101..109
        noise_seq.push(b'G'); // pos 110 = REF of 1/2
        let noise_cigar = CigarString(vec![Cigar::Match(noise_seq.len() as u32)]);
        reads.extend((0..3).map(|_| make_bam_record(100, &noise_seq, &noise_cigar)));

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(gtp.phase.is_some(), "1/2 unresolved should be phased");
        // hap_of checks alleles[0]>0 which is biallelic-only. For 2|1 that would return H0.
        // Check directly: ALT1 (index 1 in the allele array) must be at phased position alleles[1].
        assert_eq!(
            gtp.alleles[1],
            Some(1),
            "ALT1(C) of 1/2 should be at phased GT position (alleles[1]=1), meaning it is on H1"
        );
    }

    /// Build an unphased multi-allelic het record (e.g. `1/2`). `alleles` = [REF, ALT1, ...].
    fn make_unphased_het_multi(
        writer: &Writer,
        pos: i64,
        alleles: &[&[u8]],
        gt: (u32, u32),
    ) -> InputRecord {
        let mut rec = writer.empty_record();
        let rid = rec.header().name2rid(b"chr1").unwrap();
        rec.set_rid(Some(rid));
        rec.set_pos(pos);
        rec.set_alleles(alleles).unwrap();
        rec.push_genotypes(&[
            GenotypeAllele::Unphased(gt.0 as i32),
            GenotypeAllele::Unphased(gt.1 as i32),
        ])
        .unwrap();
        InputRecord::new(rec, 0)
    }

    // ── multi-allelic allele matching ─────────────────────────────────────────

    #[test]
    fn test_index_snv_picks_each_allele() {
        use rust_htslib::bam::record::Cigar;
        let reference = reference_with(&[(102, b"A")]);
        let alleles: &[&[u8]] = &[b"A", b"T", b"C"];
        let cigar = CigarString(vec![Cigar::Match(5)]);
        // offset 2 → pos 102
        let alt1 = make_bam_record(100, b"AATAA", &cigar);
        let alt2 = make_bam_record(100, b"AACAA", &cigar);
        let refr = make_bam_record(100, b"AAAAA", &cigar);
        let other = make_bam_record(100, b"AAGAA", &cigar);
        assert_eq!(allele_index_of(&reference, &alt1, 102, alleles, 0), Some(1));
        assert_eq!(allele_index_of(&reference, &alt2, 102, alleles, 0), Some(2));
        assert_eq!(allele_index_of(&reference, &refr, 102, alleles, 0), Some(0));
        assert_eq!(allele_index_of(&reference, &other, 102, alleles, 0), None);
    }

    #[test]
    fn test_index_alt2_not_mistaken_for_alt1() {
        use rust_htslib::bam::record::Cigar;
        // A read carrying ALT2 must not be reported as ALT1.
        let reference = reference_with(&[(102, b"A")]);
        let alleles: &[&[u8]] = &[b"A", b"T", b"C"];
        let rec = make_bam_record(100, b"AACAA", &CigarString(vec![Cigar::Match(5)]));
        assert_eq!(allele_index_of(&reference, &rec, 102, alleles, 0), Some(2));
    }

    #[test]
    fn test_index_insertion_discrimination() {
        use rust_htslib::bam::record::Cigar;
        // REF=A, ALT1=AT (ins T), ALT2=AG (ins G) at pos=100.
        let reference = reference_with(&[(100, b"AC")]);
        let alleles: &[&[u8]] = &[b"A", b"AT", b"AG"];
        let cigar = CigarString(vec![Cigar::Match(1), Cigar::Ins(1), Cigar::Match(1)]);
        let ins_t = make_bam_record(100, b"ATC", &cigar);
        let ins_g = make_bam_record(100, b"AGC", &cigar);
        assert_eq!(
            allele_index_of(&reference, &ins_t, 100, alleles, 0),
            Some(1)
        );
        assert_eq!(
            allele_index_of(&reference, &ins_g, 100, alleles, 0),
            Some(2)
        );
    }

    #[test]
    fn test_index_deletion_length_discrimination() {
        use rust_htslib::bam::record::Cigar;
        // REF=ATG, ALT1=A → deletion of "TG" at 101.
        let reference = reference_with(&[(100, b"ATGC")]);
        let alleles: &[&[u8]] = &[b"ATG", b"A"];
        // Exact-length deletion (Del 2) → ALT1.
        let del2 = make_bam_record(
            100,
            b"AC",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(2), Cigar::Match(1)]),
        );
        // Wrong-length deletion (Del 1) must NOT be credited to the len-2 ALT.
        let del1 = make_bam_record(
            100,
            b"AGC",
            &CigarString(vec![Cigar::Match(1), Cigar::Del(1), Cigar::Match(2)]),
        );
        assert_eq!(allele_index_of(&reference, &del2, 100, alleles, 0), Some(1));
        assert_eq!(
            allele_index_of(&reference, &del1, 100, alleles, 0),
            None,
            "a different-length deletion is not this ALT"
        );
    }

    // ── native multi-allelic resolve_phasing tests ────────────────────────────

    #[test]
    fn test_resolve_1_2_anchor_alt2_evidence() {
        use rust_htslib::bam::record::Cigar;
        // Anchor: 1|2 at pos=100, alleles=[A,T,C] → H0=T(ALT1), H1=C(ALT2).
        // Only ALT2 (C) reads cover the anchor — invisible to the old biallelic algorithm.
        // Unresolved: 0/1 at pos=110, REF=G ALT=A. Reads carry C@100 (anchor H1) + A@110.
        // Expected: unresolved resolves to H1.
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het_multi(&w, 100, &[b"A", b"T", b"C"], (1, 2), 100);
        let unresolved = make_unphased_het(&w, 110, b"G", b"A");
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unresolved)];

        let mut seq = vec![b'C']; // ALT2 of anchor = H1
        seq.extend(b"AAAAAAAAA");
        seq.push(b'A'); // ALT of unresolved
        let cigar = CigarString(vec![Cigar::Match(seq.len() as u32)]);
        let reads: Vec<bam::Record> = (0..3)
            .map(|_| make_bam_record(100, &seq, &cigar.clone()))
            .collect();

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(gtp.phase.is_some(), "unresolved should be phased");
        assert_eq!(
            hap_of(&gtp),
            Some(Haplotype::H1),
            "ALT2 of 1|2 anchor is on H1 → unresolved ALT should be H1"
        );
    }

    #[test]
    fn test_resolve_native_1_2_unresolved_by_alt2() {
        use rust_htslib::bam::record::Cigar;
        // Anchor: 0|1 at pos=100, REF=A ALT=T → H1=ALT1=T.
        // Unresolved: 1/2 at pos=110, alleles=[G,C,A] → ALT1=C, ALT2=A.
        // Reads carry T@100 (anchor H1) and ALT2=A@110.
        // Expected: ALT2(A) lands on H1 → GT written 1|2 → alleles[1]=Some(2).
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let anchor = make_phased_het(&w, 100, b"A", b"T", Haplotype::H1, 100);
        let unresolved = make_unphased_het_multi(&w, 110, &[b"G", b"C", b"A"], (1, 2));
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(anchor), Arc::new(unresolved)];

        let mut seq = vec![b'T']; // ALT1 of anchor = H1
        seq.extend(b"AAAAAAAAA");
        seq.push(b'A'); // ALT2 of 1/2
        let cigar = CigarString(vec![Cigar::Match(seq.len() as u32)]);
        let reads: Vec<bam::Record> = (0..3)
            .map(|_| make_bam_record(100, &seq, &cigar.clone()))
            .collect();

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        let gtp = input[1].gt();
        assert!(gtp.phase.is_some(), "1/2 unresolved should be phased");
        assert_eq!(
            gtp.alleles[1],
            Some(2),
            "ALT2(A) co-occurs with anchor H1 → ALT2 at phased position (alleles[1]=2)"
        );
    }

    #[test]
    fn test_resolve_no_anchor_pair_of_1_2() {
        use rust_htslib::bam::record::Cigar;
        // Two 1/2 records, no anchors. r1=[A,T,C]@100, r2=[G,C,A]@110.
        // Reads carry ALT1 of each (T@100, C@110) → co-occurrence links them.
        let h = make_vcf_header();
        let w = Writer::from_stdout(&h, true, bcf::Format::Vcf).unwrap();
        let r1 = make_unphased_het_multi(&w, 100, &[b"A", b"T", b"C"], (1, 2));
        let r2 = make_unphased_het_multi(&w, 110, &[b"G", b"C", b"A"], (1, 2));
        let mut input: Vec<Arc<InputRecord>> = vec![Arc::new(r1), Arc::new(r2)];

        let mut seq = vec![b'T']; // ALT1 of r1
        seq.extend(b"AAAAAAAAA");
        seq.push(b'C'); // ALT1 of r2
        let cigar = CigarString(vec![Cigar::Match(seq.len() as u32)]);
        let reads: Vec<bam::Record> = (0..3)
            .map(|_| make_bam_record(100, &seq, &cigar.clone()))
            .collect();

        let dir = tempfile::tempdir().unwrap();
        let bam_path = dir.path().join("test.bam");
        write_bam_and_index(reads, &bam_path);
        let mut reader = make_indexed_reader(&bam_path);
        let region = make_region(90, 50);

        let reference = reference_for(&input);
        resolve_phasing(
            &mut input,
            &region,
            &mut reader,
            &lenient_settings(),
            RefSlice::new(&reference, 0),
        )
        .unwrap();
        assert!(input[0].gt().phase.is_some(), "r1 should be resolved");
        assert!(input[1].gt().phase.is_some(), "r2 should be resolved");
    }
}