ferro-hgvs 1.0.0

HGVS variant normalizer - part of the ferro bioinformatics toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
//! HGVS to SPDI conversion.
//!
//! This module provides conversion functions between HGVS and SPDI formats.
//!
//! # Coordinate Systems
//!
//! - HGVS uses 1-based coordinates (see [`OneBasedPos`])
//! - SPDI uses 0-based interbase coordinates (see [`ZeroBasedPos`])
//!
//! For a variant at genomic position 12345 (1-based):
//! - HGVS: `NC_000001.11:g.12345A>G`
//! - SPDI: `NC_000001.11:12344:A:G` (0-based)
//!
//! # Supported Conversions
//!
//! | HGVS | SPDI | Provider |
//! |------|------|----------|
//! | Substitution `g.12345A>G` | `seq:12344:A:G` | not required |
//! | Deletion `g.100_102del` | `seq:99:ATG:` | required (short form) |
//! | Deletion `g.100_102delATG` | `seq:99:ATG:` | not required (explicit form) |
//! | Insertion `g.100_101insATG` | `seq:100::ATG` | not required |
//! | Delins `g.100_102delinsATG` | `seq:99:ATG:ATG` | required |
//! | Duplication `g.100_102dup` | `seq:102::ATG` | required (short form) |
//! | Duplication `g.100_102dupATG` | `seq:102::ATG` | not required (explicit form) |
//! | Inversion `g.100_102inv` | `seq:99:ATG:CAT` | required (short form) |
//! | Inversion `g.100_102invATG` | `seq:99:ATG:CAT` | not required (explicit form) |
//! | Repeat `g.100_105AT[5]` | `seq:99:ATATAT:ATATATATAT` | required |
//!
//! Short-form deletions, delins, duplications, inversions, and repeats use
//! [`hgvs_to_spdi`] with a [`ReferenceProvider`] to fetch reference bases for
//! SPDI's mandatory `del` (or, for duplication, `ins`) field. Explicit forms
//! do not consult the provider.
//!
//! SPDI has no native `inv` or repeat shape; both convert to `delins`. The
//! inverse direction ([`spdi_to_hgvs`]) is therefore lossy for these edits —
//! an SPDI built from `g.100_102inv` round-trips back to
//! `g.100_102delinsCAT`, not to `inv`. Detecting reverse-complement and
//! repeat structure on input SPDI is tracked in #81 (items A2, B1).
//!
//! # Coordinate-system support
//!
//! [`hgvs_to_spdi_simple`] accepts coordinate systems whose positions are
//! resolvable without provider data:
//!
//! - `g.` (genomic) — direct, for a position that names a coordinate. A
//!   `+`/`-` offset (#1628) or a `pter`/`qter`/`cen` (#1643) is refused
//!   wherever it is written, a complex `(a_b)` boundary included, and an end
//!   boundary that names no single coordinate — `(a_b)` or `?` — is refused
//!   rather than collapsed onto the start (#1795).
//! - `m.` (mito) — the mito accession is genomic; same path as `g.`.
//!   Wraparound ranges (`start > end`) on circular references are rejected
//!   per issue #399 — SPDI has no native wraparound representation.
//! - `o.` (circular) — same path as `g.`/`m.`; wraparound ranges rejected
//!   as above.
//! - `n.` (non-coding tx) — exonic, positive base; SPDI on the transcript
//!   accession.
//! - `r.` (RNA) — exonic, positive base; `u`/`U` rewritten to `T` for
//!   SPDI's DNA alphabet convention.
//!
//! [`hgvs_to_spdi`] additionally handles `c.` (CDS) and UTR-style
//! `n.`/`r.` positions by consulting a [`ReferenceProvider`] for transcript
//! metadata, and uses the same provider to fetch reference bases for
//! short-form `Deletion` / `Duplication` / `Delins` edits across all
//! coordinate systems. Intronic `n.`/`r.` positions remain unsupported
//! (SPDI has no offset notation; genomic projection is future work). Per
//! the [SPDI spec], the SPDI accession matches the HGVS accession (NCBI
//! Variation Services emits SPDI on transcript accessions the same way).
//!
//! `p.` (protein) variants are not representable in SPDI and are rejected.
//!
//! [`ReferenceProvider`]: crate::reference::provider::ReferenceProvider
//! [SPDI spec]: https://www.ncbi.nlm.nih.gov/variation/notation/
//!
//! [`OneBasedPos`]: crate::coords::OneBasedPos
//! [`ZeroBasedPos`]: crate::coords::ZeroBasedPos

use super::SpdiVariant;
use crate::convert::CoordinateMapper;
use crate::coords::{OneBasedPos, ZeroBasedPos};
use crate::error::FerroError;
use crate::hgvs::edit::{InsertedSequence, NaEdit, RepeatCount, Sequence};
use crate::hgvs::interval::{Interval, UncertainBoundary};
use crate::hgvs::location::{CdsPos, GenomePos, RnaPos, TxPos};
use crate::hgvs::parser::accession::parse_accession;
use crate::hgvs::variant::{
    Accession, CdsVariant, CircularVariant, GenomeVariant, HgvsVariant, LocEdit, MtVariant,
    RnaVariant, TxVariant,
};
use crate::normalize::rules::InsCoordKind;
use crate::reference::provider::ReferenceProvider;
use crate::reference::transcript::Transcript;
use crate::sequence::reverse_complement;

/// Maximum number of bases allowed in an SPDI `ins` string emitted from a
/// repeat expansion. The repeat count is user-controlled (HGVS `RepeatCount`
/// is a `u64`), so an unbounded `unit.repeat(count)` can be forced into a
/// huge allocation. 100 KB is well above any biological tandem-repeat tract
/// we'd plausibly emit as a single SPDI.
const MAX_REPEAT_EXPANSION_BASES: usize = 100_000;

/// Widest reference window [`resolve_repeat_tract_span`] will read while looking
/// for the physical extent of a start-only repeat anchor.
///
/// Named separately from [`MAX_REPEAT_EXPANSION_BASES`] because it bounds a
/// different thing: that one caps the `ins` string a repeat *count* can
/// generate, this one caps how much reference is *read* to find the tract the
/// anchor names. Reusing the expansion bound for both read as if one number
/// governed both, and the growth loop compared it against a half-width, so the
/// window it declined at was twice the figure its own error message quoted.
///
/// 200 KB is far above any biological tandem repeat — the largest known
/// pathogenic expansions run to a few tens of kilobases — so a tract still
/// growing at this width is a degenerate reference, not a variant.
const MAX_REPEAT_SEARCH_BASES: u64 = 200_000;

/// Error type for conversion failures.
///
/// Marked `#[non_exhaustive]` so a new conversion-failure case is additive
/// rather than breaking for downstream crates matching on it — the same
/// treatment [`crate::FerroError`] and [`crate::error::ErrorCode`] received in
/// #1033.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConversionError {
    /// The variant type is not supported for conversion.
    UnsupportedVariantType {
        /// Description of the unsupported type.
        description: String,
    },
    /// Missing reference sequence data needed for conversion.
    MissingReferenceData {
        /// Description of what data is missing.
        description: String,
    },
    /// The edit type is not supported for conversion.
    UnsupportedEditType {
        /// Description of the unsupported edit.
        description: String,
    },
    /// Invalid position or interval.
    InvalidPosition {
        /// Description of the position error.
        description: String,
    },
    /// Invalid accession format.
    InvalidAccession {
        /// Description of the accession error.
        description: String,
    },
    /// A reference provider is required to perform this conversion, but none
    /// was supplied. Distinct from [`MissingReferenceData`], which means a
    /// provider was supplied but does not have data for the requested region.
    ///
    /// [`MissingReferenceData`]: ConversionError::MissingReferenceData
    ProviderRequired {
        /// HGVS coordinate-system letter that triggered the error (`c`, `n`, `r`, ...).
        variant_type: String,
        /// Why a provider is needed for this variant.
        reason: String,
    },
    /// SPDI cannot express the description at all — a limit of the *target
    /// representation*, decided from the description alone.
    ///
    /// The distinction from its two reference-flavoured siblings is what a
    /// better-provisioned provider would buy you: [`ProviderRequired`] is
    /// answered by supplying a provider and [`MissingReferenceData`] by
    /// supplying one that holds the region, while **no** provider answers this
    /// one, because nothing is missing. SPDI is positional and has no offset
    /// notation, so an intronic transcript position (`c.10+5`, `n.10+5`,
    /// `r.10+5`) names no coordinate on the transcript accession however
    /// completely that accession is served.
    ///
    /// Consumers classifying a conversion failure as "could not tell" versus
    /// "decided negative" must read this as the latter — see
    /// `equivalence::checker`'s `TripleDecline::from_conversion_error`, which
    /// is where routing these three sites through `MissingReferenceData`
    /// turned four decided verdicts into refusals on a fully served reference
    /// (#2056 follow-up).
    ///
    /// [`MissingReferenceData`]: ConversionError::MissingReferenceData
    /// [`ProviderRequired`]: ConversionError::ProviderRequired
    UnrepresentableInSpdi {
        /// What cannot be expressed, and why.
        description: String,
    },
}

impl std::fmt::Display for ConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConversionError::UnsupportedVariantType { description } => {
                write!(
                    f,
                    "unsupported variant type for conversion: {}",
                    description
                )
            }
            ConversionError::MissingReferenceData { description } => {
                write!(f, "missing reference data: {}", description)
            }
            ConversionError::UnsupportedEditType { description } => {
                write!(f, "unsupported edit type for conversion: {}", description)
            }
            ConversionError::InvalidPosition { description } => {
                write!(f, "invalid position: {}", description)
            }
            ConversionError::InvalidAccession { description } => {
                write!(f, "invalid accession: {}", description)
            }
            ConversionError::ProviderRequired {
                variant_type,
                reason,
            } => {
                write!(
                    f,
                    "reference provider required to convert {}. variant: {}",
                    variant_type, reason
                )
            }
            ConversionError::UnrepresentableInSpdi { description } => {
                write!(f, "cannot be expressed in SPDI: {}", description)
            }
        }
    }
}

impl std::error::Error for ConversionError {}

impl From<ConversionError> for FerroError {
    fn from(err: ConversionError) -> Self {
        FerroError::ConversionError {
            msg: err.to_string(),
        }
    }
}

/// Helper to convert a Sequence to a String.
fn sequence_to_string(seq: &Sequence) -> String {
    seq.to_string()
}

/// Helper to convert an InsertedSequence to a String (for literal sequences only).
fn inserted_sequence_to_string(seq: &InsertedSequence) -> Option<String> {
    match seq {
        InsertedSequence::Literal(s) => Some(s.to_string()),
        _ => None,
    }
}

/// Translate one insert-payload coordinate from the axis it is **written** on
/// onto the transcript axis the SPDI is emitted on.
///
/// A payload position is spelled in the description's own coordinate system —
/// `c.156_157ins180_188` names `c.180` through `c.188`, not transcript 180
/// through 188 — while the accession this function's caller fetches against is
/// the flat transcript. So on a CDS-relative axis the payload needs exactly the
/// `cds_start + N - 1` shift [`resolve_cds_to_tx`] already applies to the
/// *location*, and it is routed through the same [`CoordinateMapper::cds_to_tx`]
/// so the two cannot drift apart (the property #390-follow-up / #944 established
/// for `r.*N` and `c.*N`, and #1619's flat frame preserved).
///
/// Only plain positive positions arrive here: the `u64` `PositionRange` shape
/// cannot carry a `-N`, `*N` or intronic offset — the parser lands those in
/// `CdsPositionRange`, which this path does not accept.
fn resolve_payload_position(
    accession: &str,
    transcript: &Transcript,
    pos: u64,
    coord: &str,
) -> Result<u64, ConversionError> {
    let base = i64::try_from(pos).map_err(|_| ConversionError::InvalidPosition {
        description: format!(
            "{coord}. insert payload position {pos} on {accession} exceeds the addressable range"
        ),
    })?;
    let mapper = CoordinateMapper::new(transcript);
    let tx = mapper.cds_to_tx(&CdsPos::new(base)).map_err(|e| {
        ConversionError::MissingReferenceData {
            description: format!(
                "could not resolve {coord}. insert payload position {pos} on {accession} \
                 to a transcript position: {e}"
            ),
        }
    })?;
    let one_based = ensure_positive_tx(tx.base, coord, pos)?;
    if one_based > transcript.sequence_length() {
        return Err(ConversionError::InvalidPosition {
            description: format!(
                "{coord}. insert payload position {pos} on {accession} resolves to transcript \
                 base {one_based}, past the transcript 3' end (length {})",
                transcript.sequence_length()
            ),
        });
    }
    Ok(one_based)
}

/// Translate an insert payload's `(start, end)` span onto the transcript axis,
/// per the axis the enclosing description is written on.
///
/// `Direct` (`g.`/`m.`/`o.`/`n.`) passes the positions through unchanged — a
/// genomic coordinate and a non-coding transcript coordinate are already offsets
/// on the accession being fetched. `Cds` shifts through the transcript's CDS
/// start. `Rna` follows the associated DNA numbering — CDS-relative on a coding
/// transcript, transcript-relative on a non-coding one — which is the same split
/// [`resolve_rna_pos`] makes for the *location*, so a payload and a location on
/// one description are read in one frame.
fn resolve_payload_span<P>(
    accession: &str,
    start: u64,
    end: u64,
    kind: InsCoordKind,
    provider: &P,
) -> Result<(u64, u64), ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let coord = match kind {
        InsCoordKind::Direct => return Ok((start, end)),
        InsCoordKind::Cds => "c",
        InsCoordKind::Rna => "r",
    };
    let transcript =
        provider
            .get_transcript(accession)
            .map_err(|e| ConversionError::MissingReferenceData {
                description: format!(
                    "could not load transcript {accession} to resolve the {coord}. insert \
                     payload {start}_{end}: {e}"
                ),
            })?;
    // `r.` on a non-coding transcript has no CDS to be relative to, so its
    // positions are already transcript offsets. Mirrors `resolve_rna_pos`.
    if kind == InsCoordKind::Rna && transcript.cds_start.is_none() {
        return Ok((start, end));
    }
    Ok((
        resolve_payload_position(accession, &transcript, start, coord)?,
        resolve_payload_position(accession, &transcript, end, coord)?,
    ))
}

/// Read a same-reference span `[start, end]` (1-based inclusive) to its literal
/// bases, reverse-complementing when `invert`, and fold the result through the
/// output alphabet — the one place the fetch-invert-fold logic lives.
///
/// Both the top-level `ins50_57`/`ins50_57inv` shape and a `[…;213_271;…]`
/// bracket part resolve through here, so a coordinate span reads identically
/// however it was spelled. Declines with `MissingReferenceData` when no provider
/// is available to read the span, propagating any fetch failure otherwise.
fn read_reference_span<P>(
    accession: &str,
    start: u64,
    end: u64,
    invert: bool,
    alphabet: AlphabetMode,
    kind: InsCoordKind,
    provider: Option<&P>,
) -> Result<String, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let provider = provider.ok_or_else(|| ConversionError::MissingReferenceData {
        description: format!(
            "position-range insertion {start}_{end} names bases in the same reference; \
             a provider is required to read them"
        ),
    })?;
    // `start`/`end` are written in the enclosing description's own coordinate
    // system; the fetch is on the accession the SPDI is emitted against.
    let (start, end) = resolve_payload_span(accession, start, end, kind, provider)?;
    let bases = fetch_reference_bases(provider, accession, start, end)?;
    let bases = if invert {
        reverse_complement(&bases)
    } else {
        bases
    };
    Ok(apply_alphabet(&bases, alphabet))
}

/// Refuse a repeat whose unit carries undetermined content — an `N` (or `n`)
/// anywhere in the spelled unit.
///
/// An `N` names a *length*, not bases, so expanding an `N`-unit repeat into an
/// SPDI insertion string asserts specific bases the input never specified:
/// `insN[341]` would emit 341 literal `N`s, a triple a consumer can store keyed
/// on 341 bases that do not exist. That is the same information content as the
/// `ins<length>` shape (`ins341`, [`InsertedSequence::Count`]) this module
/// already refuses (#1967), so it is refused here too — consistent with the
/// #1747 precedent that a plausible-but-wrong SPDI triple is worse than a clean
/// decline. The determination is made from the description alone and no provider
/// can change it, so the error is [`ConversionError::UnrepresentableInSpdi`].
///
/// A concrete-base unit (`insACGT[3]`, `insA[10]`) states its bases exactly and
/// passes through — only undetermined content is refused. Ruling
/// `spdi-n-unit-repeat-refusal` in `hgvs_spec_normalization_overrides.json`.
fn refuse_undetermined_repeat_unit(unit: &str) -> Result<(), ConversionError> {
    if unit.bytes().any(|b| b.eq_ignore_ascii_case(&b'N')) {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: format!(
                "repeat unit `{unit}` contains an undetermined base (`N`); it names a length, \
                 not bases, so expanding it would assert bases the input never specified. Like \
                 `ins<length>`, an undetermined-content repeat is refused rather than emitted \
                 as a run of `N`s"
            ),
        });
    }
    Ok(())
}

/// Expand a repeat `unit` `count` times, folded through the output alphabet —
/// the one place the overflow and [`MAX_REPEAT_EXPANSION_BASES`] cap checks
/// live, so a top-level `insA[10]` and a `[…;A[10];…]` bracket part expand
/// identically. `unit` is the literal unit spelled once.
///
/// An `N`-carrying unit is refused here (see [`refuse_undetermined_repeat_unit`])
/// rather than expanded into a run of `N`s.
fn expand_repeat_unit(
    unit: &str,
    count: u64,
    alphabet: AlphabetMode,
) -> Result<String, ConversionError> {
    let unit = apply_alphabet(unit, alphabet);
    refuse_undetermined_repeat_unit(&unit)?;
    let count = count as usize;
    let expansion_bases =
        unit.len()
            .checked_mul(count)
            .ok_or_else(|| ConversionError::UnsupportedEditType {
                description: format!(
                    "repeat expansion {} x {} overflows usize",
                    unit.len(),
                    count
                ),
            })?;
    if expansion_bases > MAX_REPEAT_EXPANSION_BASES {
        return Err(ConversionError::UnsupportedEditType {
            description: format!(
                "repeat expansion {} bases exceeds SPDI ins-string cap of {} bases",
                expansion_bases, MAX_REPEAT_EXPANSION_BASES
            ),
        });
    }
    Ok(unit.repeat(count))
}

/// Resolve a same-reference position-range insert (`ins50_57`, `ins50_57inv`)
/// to its literal bases by reading them from the reference, mirroring how the
/// omitted bases of `del`/`dup`/`delins` are fetched.
///
/// Returns `Ok(None)` when `seq` is not a position-range insert, so the caller
/// can fall back to literal handling. The read itself is [`read_reference_span`],
/// shared with the bracket-part path so both spell a span identically.
fn resolve_position_range_insert<P>(
    seq: &InsertedSequence,
    accession: &str,
    alphabet: AlphabetMode,
    kind: InsCoordKind,
    provider: Option<&P>,
) -> Result<Option<String>, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let Some((start, end, invert)) = seq.as_position_range() else {
        return Ok(None);
    };
    read_reference_span(accession, start, end, invert, alphabet, kind, provider).map(Some)
}

/// An inserted sequence whose bases are an exact tandem repeat, decomposed to
/// `(unit, count)` — the literal unit spelled once and the exact number of
/// copies — or `None` when `seq` is not one.
///
/// Recognises the single-base `Repeat` (`insA[10]`), the multi-base
/// `SequenceRepeat` (`insAT[3]`), and the single-part `Complex([Repeat])` shape
/// the parser produces for a lone repeat unit. Only an [`RepeatCount::Exact`]
/// count is a determinate string of bases; every uncertain or range count
/// (`insA[10_15]`, `insA[?]`, …) names no single expansion and returns `None`,
/// so the caller keeps declining it. Multi-part `Complex` payloads and every
/// non-repeat variant also return `None`.
fn exact_repeat_insert(seq: &InsertedSequence) -> Option<(String, u64)> {
    use crate::hgvs::edit::InsertedPart;
    let exact = |count: &RepeatCount| match count {
        RepeatCount::Exact(n) => Some(*n),
        _ => None,
    };
    match seq {
        InsertedSequence::Repeat { base, count } => {
            Some((base.to_char().to_string(), exact(count)?))
        }
        InsertedSequence::SequenceRepeat { sequence, count } => {
            Some((sequence_to_string(sequence), exact(count)?))
        }
        InsertedSequence::Complex(parts) => match parts.as_slice() {
            [InsertedPart::Repeat { base, count }] => {
                Some((base.to_char().to_string(), exact(count)?))
            }
            _ => None,
        },
        _ => None,
    }
}

/// Resolve an exact tandem-repeat insert (`insA[10]`, `insAT[3]`) to its literal
/// bases by expanding the unit the named number of times, mirroring how the
/// short-form `Repeat` edit arm expands its own explicit unit and exact count.
///
/// Returns `Ok(None)` when `seq` is not an exact repeat, so the caller can fall
/// back to literal handling. The expansion itself is [`expand_repeat_unit`],
/// shared with the bracket-part path so both apply the same overflow and cap.
fn resolve_exact_repeat_insert(
    seq: &InsertedSequence,
    alphabet: AlphabetMode,
) -> Result<Option<String>, ConversionError> {
    let Some((unit, count)) = exact_repeat_insert(seq) else {
        return Ok(None);
    };
    expand_repeat_unit(&unit, count, alphabet).map(Some)
}

/// Resolve one part of a compound insert to its literal bases, dispatching each
/// determinate shape to the same leaf helper the single-part path uses.
///
/// A `PositionRange`/`PositionRangeInv` reads through [`read_reference_span`], an
/// exact `Repeat` expands through [`expand_repeat_unit`], and a `Literal` is
/// rendered directly — the same three leaves that back
/// [`resolve_position_range_insert`] and [`resolve_exact_repeat_insert`], so a
/// part spells its bases identically whether it stands alone or inside a bracket.
/// The remaining shapes name bases this path cannot yet read out and decline as
/// `UnsupportedEditType`: a non-exact repeat count (`N[2800]`, `A[10_15]`), a CDS
/// position range carrying intronic offsets, or an external reference SPDI
/// cannot dereference.
fn resolve_inserted_part<P>(
    part: &crate::hgvs::edit::InsertedPart,
    accession: &str,
    alphabet: AlphabetMode,
    kind: InsCoordKind,
    provider: Option<&P>,
) -> Result<String, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    use crate::hgvs::edit::InsertedPart;

    match part {
        InsertedPart::Literal(seq) => Ok(apply_alphabet(&seq.to_string(), alphabet)),
        InsertedPart::PositionRange { start, end } => {
            read_reference_span(accession, *start, *end, false, alphabet, kind, provider)
        }
        InsertedPart::PositionRangeInv { start, end } => {
            read_reference_span(accession, *start, *end, true, alphabet, kind, provider)
        }
        InsertedPart::Repeat {
            base,
            count: RepeatCount::Exact(n),
        } => expand_repeat_unit(&base.to_char().to_string(), *n, alphabet),
        // A non-exact `Repeat` count (`N[2800]`, `A[10_15]`) names no determinate
        // expansion.
        InsertedPart::Repeat { base, count } => Err(ConversionError::UnsupportedEditType {
            description: format!(
                "compound insert part {base}{count} has no determinate expansion; \
                 this shape is not yet encodable as SPDI"
            ),
        }),
        InsertedPart::CdsPositionRange(range) => Err(ConversionError::UnsupportedEditType {
            description: format!(
                "compound insert part {range} names CDS positions with intronic offsets; \
                 this shape is not yet encodable as SPDI"
            ),
        }),
        InsertedPart::ExternalRef(reference) => Err(ConversionError::UnsupportedEditType {
            description: format!(
                "compound insert part {reference} references an external sequence SPDI \
                 cannot dereference; this shape is not yet encodable as SPDI"
            ),
        }),
    }
}

/// Resolve a multi-part `Complex` insert whose every part names determinate
/// bases — a literal, an exact tandem repeat, or a same-reference position
/// range (optionally inverted) — to the single string of bases they spell in
/// order, mirroring how `del`/`dup` resolve their omitted bases.
///
/// This is the bracketed-composition sibling of [`resolve_position_range_insert`]
/// and [`resolve_exact_repeat_insert`], which each handle only a *single*-part
/// `Complex`. A compound insert that mixes shapes — `delins[T;213_271]`, a
/// literal followed by a reference span — is one contiguous inserted sequence
/// once each part is read out, so it encodes to SPDI just as a plain literal
/// does. Each part is resolved by [`resolve_inserted_part`], which shares its
/// leaf helpers with the single-part path, so no shape logic is duplicated.
///
/// Returns `Ok(None)` when `seq` is not a `Complex`, so the caller falls back to
/// its single-shape resolvers and literal handling. Any part whose bases are
/// genuinely undetermined declines the whole insert as `UnsupportedEditType`.
fn resolve_complex_insert<P>(
    seq: &InsertedSequence,
    accession: &str,
    alphabet: AlphabetMode,
    kind: InsCoordKind,
    provider: Option<&P>,
) -> Result<Option<String>, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let InsertedSequence::Complex(parts) = seq else {
        return Ok(None);
    };

    let mut resolved = String::new();
    for part in parts {
        resolved.push_str(&resolve_inserted_part(
            part, accession, alphabet, kind, provider,
        )?);
    }
    Ok(Some(resolved))
}

/// Helper to get start position from an interval.
fn get_start_pos(interval: &Interval<GenomePos>) -> Option<u64> {
    interval.start.inner().map(|p| p.base)
}

/// Helper to get end position from an interval.
fn get_end_pos(interval: &Interval<GenomePos>) -> Option<u64> {
    interval.end.inner().map(|p| p.base)
}

/// Every [`GenomePos`] a boundary actually **writes down**, whether or not any
/// one of them is a coordinate the conversion could use.
///
/// [`UncertainBoundary::inner`] answers a deliberately narrower question — "is
/// this one position I can resolve?" — and so returns `None` for a `Range`,
/// hiding *both* its endpoints. That is the right answer for a caller asking
/// for a coordinate and the wrong one for a caller asking what the description
/// says, and [`reject_unresolvable_genomic_position`] is the second kind: a
/// prohibited offset is prohibited wherever it is written, so
/// `g.10_(20+1_30)delACGT` carried one straight past the guard and converted
/// as though it read `g.10delACGT` (#1795).
fn stated_positions(boundary: &UncertainBoundary<GenomePos>) -> [Option<&GenomePos>; 2] {
    match boundary {
        UncertainBoundary::Single(mu) => [mu.inner(), None],
        UncertainBoundary::Range { start, end } => [start.inner(), end.inner()],
    }
}

/// Resolve a genomic interval's **end** coordinate, declining when the boundary
/// names no single position.
///
/// The call sites previously wrote `get_end_pos(..).unwrap_or(start_pos)`,
/// which is the same silent drop [`reject_unresolvable_genomic_position`] was
/// written to stop, one field over: an end that resolves to nothing — a
/// `(a_b)` range, or a bare `?` — was replaced by the start, so the interval
/// collapsed to a point and the boundary vanished from the answer. That is what
/// made `g.10_(20+1_30)delACGT`, `g.10_(20_30)delACGT` and `g.10delACGT` one
/// triple; the offset is a symptom of the dropped boundary, and closing only
/// the guard hole would have left the last two of those three still colliding.
///
/// Declining is not a new contract. The **start** side has always declined
/// (`get_start_pos(..).ok_or_else(..)`), and the VCF sibling
/// (`vcf::from_hgvs`) declines on both endpoints with no fallback at all — the
/// fallback here was the asymmetry, not the refusal. An SPDI position is an
/// exact interbase coordinate, so there is nothing an uncertain region or an
/// unknown position could be rendered as.
///
/// Note this is about a boundary that names *no* position, never about one the
/// author flagged as approximate: `(13)` is `Mu::Uncertain`, `inner()` returns
/// 13, and it resolves here exactly as a bare `13` does.
///
/// **Genomic axes only.** The `c.`/`n.`/`r.` paths carried the same fallback at
/// five further sites and collapsed the same way — measured, and deferred to
/// #1804 rather than swept in here, because those axes decide the *neighbouring*
/// question differently: a `+`/`-` offset inside a `Range` is *legitimate*
/// there (`c.(4185+1_4186-1)_(4357+1_4358-1)del`), so
/// [`reject_unresolvable_genomic_position`] cannot simply be pointed at them.
///
/// #1804 has since been closed by #1823, whose
/// [`resolve_transcript_end_boundary`] is this function's transcript-axis
/// counterpart. The two stay separate for a typing reason rather than a policy
/// one — this resolves a [`GenomePos`] to the `u64` its call sites need, while
/// that one hands the axis' own position type back for a further conversion —
/// and they agree on the verdict: both refuse with
/// [`ConversionError::InvalidPosition`]. See that function's doc for why it
/// takes that verdict from its own axis rather than inheriting it from here.
fn resolve_genomic_end_pos(
    interval: &Interval<GenomePos>,
    coord: &str,
) -> Result<u64, ConversionError> {
    get_end_pos(interval).ok_or_else(|| ConversionError::InvalidPosition {
        description: format!(
            "{coord}. end boundary `{}` names no single coordinate: an SPDI position is an \
             exact interbase coordinate, and an uncertain range or unknown (`?`) boundary \
             supplies none. Collapsing it onto the start position would make distinct \
             descriptions share one triple. Give the end a definite position, or keep the \
             description in HGVS",
            interval.end
        ),
    })
}

/// Refuse a genomic interval whose start or end holds something SPDI cannot be
/// given a coordinate for: a `+`/`-` offset (#1628) or a `pter`/`qter`/`cen`
/// special position (#1643).
///
/// The two are the same defect in two fields of one struct. `GenomePos` can
/// hold either because the parser accepts both, and neither half of the
/// conversion can honour them:
///
/// - an **offset** has nothing on a genomic accession to be measured against —
///   there is no exon structure, and `checklist.md:16` prohibits an offset on a
///   genomic position outright — and SPDI has no offset notation;
/// - a **special position** names a landmark of the assembled chromosome
///   (`pter`, `qter`) or of its centromere annotation (`cen`), none of which a
///   sequence accession carries. `GenomePos` stores `base: 0` beside the
///   `special` marker precisely because there is no coordinate to store.
///
/// What the conversion did instead was drop both, which is the one answer worse
/// than either honest option, and it produced the same confluence failure
/// twice. `g.266+2del`, `g.266-268del` and `g.266del` flattened onto one triple
/// while `normalize` keeps them as three distinct descriptions. So did
/// `g.10_qterdelACGTACGTAC`, `g.10_cendelACGTACGTAC` and
/// `g.10_19delACGTACGTAC` — a deletion to the q-arm telomere, one to the
/// centromere and a literal ten-base deletion, all `NC_000001.11:9:ACGTACGTAC:`.
///
/// **The special-position half was reachable only when the description spells
/// its own bases**, which is why it survived #1641 and why the guard is what
/// closes it rather than the checks that appear to. Every other shape happened
/// to be refused *incidentally*, by a check asking a different question:
/// `g.pter_10del` by the 1-based position check ("position 0 is not valid in
/// HGVS"), `g.10_qterdel` by the reference fetch (`invalid 1-based interval
/// [10, 0]`), and the `m.`/`o.` forms by the circular-wraparound check, which
/// reads `start > end` and reports a wraparound that is not there. Those
/// messages diagnose the wrong thing and none of them is a guarantee — a
/// description carrying its own bases needs no fetch and no position check, and
/// so converted.
///
/// **Both endpoints of a complex `(a_b)` boundary are walked, not just the
/// boundary as a whole** (#1795). The guard originally read each side through
/// [`UncertainBoundary::inner`], which reports `None` for a `Range`, so a
/// prohibited offset or special position written *inside* the parentheses was
/// never inspected: `g.10_(20+1_30)delACGT` and `g.10_(20_qter)delACGT` both
/// converted. See [`stated_positions`], which is the walk this uses and is
/// deliberately a different question from `inner()`.
///
/// Refusing is also what the other axes already do with the offsets that *are*
/// legitimate there — see [`resolve_cds_to_tx`], [`resolve_tx_pos`] and
/// [`require_simple_tx_pos`], each of which declines an intronic `c.`/`n.`/`r.`
/// position for want of an SPDI representation. Those decline because the
/// position cannot be projected onto the transcript accession; this one declines
/// because there is nothing on a genomic accession to project it against.
fn reject_unresolvable_genomic_position(
    interval: &Interval<GenomePos>,
    coord: &str,
) -> Result<(), ConversionError> {
    for endpoint in [&interval.start, &interval.end]
        .into_iter()
        .flat_map(stated_positions)
        .flatten()
    {
        if endpoint.offset.is_some() {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "{coord}. position {endpoint} carries a +/- offset: a genomic position \
                     cannot have one and SPDI has no offset notation to express it. Drop the \
                     offset, or describe the variant on a transcript accession where an offset \
                     is meaningful"
                ),
            });
        }
        if let Some(special) = endpoint.special {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "{coord}. position `{special}` names no numeric coordinate: `pter`, `qter` \
                     and `cen` are landmarks of the assembled chromosome, not positions on the \
                     sequence, and SPDI has no notation for them. Give the position a number, \
                     or keep the description in HGVS"
                ),
            });
        }
    }
    Ok(())
}

/// Convert an HGVS variant to SPDI format without consulting a reference provider.
///
/// This is the "simple" conversion path: the SPDI is emitted on the same
/// accession the HGVS variant uses (no genomic projection of transcript
/// variants). It accepts coordinate systems whose positions can be resolved
/// without transcript metadata:
///
/// | HGVS coord | Supported here | Notes |
/// |------------|----------------|-------|
/// | `g.` (genomic) | yes | direct 1→0-based conversion; a `+`/`-` offset (#1628) or a `pter`/`qter`/`cen` (#1643) is refused wherever it is written, inside a complex `(a_b)` boundary included, and an end boundary naming no single coordinate — `(a_b)` or `?` — is refused rather than collapsed onto the start (#1795) |
/// | `m.` (mito) | yes | mito accession is genomic; same as `g.`; wraparound rejected |
/// | `o.` (circular) | yes | same path as `g.`/`m.`; wraparound rejected |
/// | `n.` (non-coding tx) | exonic, positive base | SPDI sits on the transcript accession |
/// | `r.` (RNA) | exonic, positive base | `u`/`U` rewritten to `T`; SPDI uses DNA alphabet |
/// | `c.` (CDS) | NO — needs CDS start | use [`hgvs_to_spdi`] |
/// | `p.` (protein) | NO | not representable in SPDI |
///
/// For `c.`, UTR-style `n.`/`r.`, or deletion/dup variants without an
/// explicit deleted sequence, use [`hgvs_to_spdi`] which consults a
/// [`ReferenceProvider`]. Intronic `n.`/`r.` positions are not supported
/// by either entry point — SPDI has no offset notation, and genomic
/// projection is future work; both functions return
/// [`ConversionError::MissingReferenceData`]. A `g.`/`m.`/`o.` position
/// carrying an offset (#1628) or a `pter`/`qter`/`cen` special position
/// (#1643) is refused outright by both entry points with
/// [`ConversionError::InvalidPosition`]: neither has anything on a genomic
/// accession to resolve it against, and dropping either made distinct
/// descriptions share one triple. That holds **wherever the position is
/// written**, including inside a complex `(a_b)` boundary (#1795).
///
/// A `g.`/`m.`/`o.` **end** boundary that names no single coordinate — a
/// `(a_b)` range or a bare `?` — is likewise refused with
/// [`ConversionError::InvalidPosition`] rather than collapsed onto the start
/// position, which is what the start side has always done. An uncertain but
/// numeric position (`(13)`) names a coordinate and still converts. On the
/// **transcript** axes, a `c.`/`n.`/`r.` interval whose **end** names no single
/// coordinate is refused with the same variant (#1804); see
/// [`resolve_transcript_end_boundary`] for why those axes need their own
/// resolver rather than the genomic guard.
///
/// # Arguments
///
/// * `variant` - The HGVS variant to convert.
///
/// # Returns
///
/// * `Ok(SpdiVariant)` - Successfully converted variant.
/// * `Err(ConversionError::ProviderRequired)` - The variant requires a
///   provider (typically `c.` or intronic `n.`/`r.`).
/// * `Err(ConversionError)` - Conversion failed for another reason.
///
/// # Examples
///
/// ```
/// use ferro_hgvs::spdi::convert::hgvs_to_spdi_simple;
/// use ferro_hgvs::parse_hgvs;
///
/// // Genomic variant
/// let hgvs = parse_hgvs("NC_000001.11:g.12345A>G").unwrap();
/// let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
/// assert_eq!(spdi.to_string(), "NC_000001.11:12344:A:G");
///
/// // Non-coding transcript: SPDI emitted on the transcript accession
/// let hgvs = parse_hgvs("NR_046018.2:n.5C>G").unwrap();
/// let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
/// assert_eq!(spdi.to_string(), "NR_046018.2:4:C:G");
/// ```
///
/// [`ReferenceProvider`]: crate::reference::provider::ReferenceProvider
pub fn hgvs_to_spdi_simple(variant: &HgvsVariant) -> Result<SpdiVariant, ConversionError> {
    match variant {
        HgvsVariant::Genome(g) => genome_to_spdi_simple(g),
        HgvsVariant::Mt(m) => mt_to_spdi_simple(m),
        HgvsVariant::Circular(o) => circular_to_spdi_simple(o),
        HgvsVariant::Tx(n) => tx_to_spdi_simple(n),
        HgvsVariant::Rna(r) => rna_to_spdi_simple(r),
        HgvsVariant::Cds(_) => Err(ConversionError::ProviderRequired {
            variant_type: "c".to_string(),
            reason:
                "CDS positions need transcript metadata (CDS start) to resolve to a transcript \
                 position; call hgvs_to_spdi with a ReferenceProvider"
                    .to_string(),
        }),
        HgvsVariant::Protein(_) => Err(ConversionError::UnsupportedVariantType {
            description: "protein variants cannot be represented in SPDI; SPDI describes \
                          nucleotide variants on a sequence accession"
                .to_string(),
        }),
        _ => Err(ConversionError::UnsupportedVariantType {
            description: format!(
                "variant type {} cannot be converted to SPDI",
                variant.variant_type()
            ),
        }),
    }
}

/// Convert an HGVS variant to SPDI, consulting a reference provider for
/// transcript metadata (CDS start, exon coordinates) and for the deleted /
/// duplicated bases of short-form `Deletion`, `Duplication`, and `Delins`
/// edits.
///
/// This is the provider-aware companion to [`hgvs_to_spdi_simple`]. It
/// handles `c.` (CDS) variants, `n.`/`r.` variants with UTR-style positions
/// (`*N` downstream), and populates SPDI's mandatory `del` field for
/// short-form deletions / delins / identities (and the symmetric `ins` field
/// for short-form duplications) by fetching the reference bases for the
/// variant's interval. Explicit-form input (`g.100_102delATG`,
/// `g.100_102dupATG`, `g.100A=`, etc.) emits the user-supplied bases as-is
/// and does not consult the provider. Intronic `n.`/`r.` positions remain
/// unsupported (SPDI has no offset notation) and return
/// [`ConversionError::MissingReferenceData`]. An offset or a `pter`/`qter`/`cen`
/// special position on a `g.`/`m.`/`o.` position is refused with
/// [`ConversionError::InvalidPosition`] — see
/// [`reject_unresolvable_genomic_position`], which reads inside a complex
/// `(a_b)` boundary as well as a simple one. A genomic end boundary that names
/// no single coordinate is refused by [`resolve_genomic_end_pos`] rather than
/// collapsed onto the start. A `c.`/`n.`/`r.` interval whose **end** names no
/// single coordinate — a range boundary `(20_30)` or an unknown `?` — is
/// refused with the same variant (#1804); see
/// [`resolve_transcript_end_boundary`].
///
/// An **unspelled identity** (`g.100=`, `g.100_102=`) therefore needs a
/// provider: on [`hgvs_to_spdi_simple`] it returns
/// [`ConversionError::MissingReferenceData`] rather than a zero-width triple
/// that would claim no bases. A **whole-entity** identity (`g.=`) names no
/// interval at all and returns [`ConversionError::UnsupportedEditType`].
///
/// The resulting SPDI uses the **same accession** as the HGVS variant — for
/// `NM_000088.3:c.1A>G` the SPDI sequence is `NM_000088.3`, not the
/// underlying genomic accession. This matches NCBI Variation Services'
/// behavior: SPDI is positional on whichever accession is provided. No axis is
/// projected onto another.
///
/// The one thing that is *not* carried over verbatim is a **compound
/// reference's genomic-context wrapper** on a transcript axis: for
/// `NG_008939.1(NM_000532.5):c.156A>G` the SPDI sequence is `NM_000532.5`. That
/// is not a projection either — it is the accession this function already
/// resolved the position against, and naming the wrapper instead pointed every
/// downstream fetch at the genomic parent. See [`transcript_axis_sequence`]. A
/// `g.`/`m.`/`o.` description keeps its accession exactly as written.
///
/// # Arguments
///
/// * `variant` - The HGVS variant to convert.
/// * `provider` - A reference provider used both for transcript metadata
///   (`get_transcript`) and reference-base fetches for short-form edits
///   (`get_genomic_sequence` first, then `get_sequence` as fallback).
///
/// # Errors
///
/// * [`ConversionError::MissingReferenceData`] if the provider does not
///   have the transcript or the requested reference interval, or if the
///   position cannot be resolved (e.g. intronic without exon data).
/// * Other `ConversionError` variants for the same reasons as
///   [`hgvs_to_spdi_simple`].
///
/// # Examples
///
/// Short-form deletion with provider-backed ref fetch:
///
/// ```
/// use ferro_hgvs::spdi::convert::hgvs_to_spdi;
/// use ferro_hgvs::reference::mock::MockProvider;
/// use ferro_hgvs::parse_hgvs;
///
/// let mut provider = MockProvider::new();
/// // Build a contig where 1-based 100..102 = "ATG".
/// let mut seq = "N".repeat(99);
/// seq.push_str("ATG");
/// provider.add_genomic_sequence("NC_000001.11", &seq);
///
/// let hgvs = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
/// let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
/// assert_eq!(spdi.to_string(), "NC_000001.11:99:ATG:");
/// ```
pub fn hgvs_to_spdi<P: ReferenceProvider + ?Sized>(
    variant: &HgvsVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    match variant {
        HgvsVariant::Genome(g) => genome_to_spdi_with_provider(g, provider),
        HgvsVariant::Mt(m) => mt_to_spdi_with_provider(m, provider),
        HgvsVariant::Circular(o) => circular_to_spdi_with_provider(o, provider),
        HgvsVariant::Tx(n) => tx_to_spdi_with_provider(n, provider),
        HgvsVariant::Rna(r) => rna_to_spdi_with_provider(r, provider),
        HgvsVariant::Cds(c) => cds_to_spdi_with_provider(c, provider),
        HgvsVariant::Protein(_) => Err(ConversionError::UnsupportedVariantType {
            description: "protein variants cannot be represented in SPDI; SPDI describes \
                          nucleotide variants on a sequence accession"
                .to_string(),
        }),
        _ => Err(ConversionError::UnsupportedVariantType {
            description: format!(
                "variant type {} cannot be converted to SPDI",
                variant.variant_type()
            ),
        }),
    }
}

/// Convert a genomic variant to SPDI (simple conversion).
fn genome_to_spdi_simple(variant: &GenomeVariant) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "g")?;
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "g")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        None::<&dyn ReferenceProvider>,
    )
}

/// Convert a mitochondrial variant to SPDI (simple conversion).
///
/// Mitochondrial accessions (e.g. `NC_012920.1`) are themselves genomic
/// accessions, so the conversion is identical to the `g.` path with a
/// different coordinate prefix on the HGVS side.
///
/// Wraparound variants (start > end, per SVD-WG006) are rejected: SPDI is a
/// single-edit format with no native representation for circular-contig
/// wraparound.
fn mt_to_spdi_simple(variant: &MtVariant) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "m")?;
    if let (Some(s), Some(e)) = (
        get_start_pos(&variant.loc_edit.location),
        get_end_pos(&variant.loc_edit.location),
    ) {
        if s > e {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "Cannot convert wraparound m. variant to SPDI: SPDI is a single edit and \
                     has no representation for circular-contig wraparound. Variant accession: {}",
                    variant.accession
                ),
            });
        }
    }
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "m")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        None::<&dyn ReferenceProvider>,
    )
}

/// The accession a **transcript-axis** (`c.`/`n.`/`r.`) SPDI is emitted on: the
/// inner transcript, with any `NG_`/`NC_`/`LRG_` genomic-context wrapper
/// stripped.
///
/// This is the same string the coordinate resolution already uses — see
/// [`resolve_cds_to_tx`], which calls `accession.transcript_accession()`, reads
/// that transcript's `cds_start`, and bounds the result against *that*
/// transcript's length. So the number `emit_spdi_for_edit` receives is an offset
/// on the transcript, and this makes the accession beside it say so.
///
/// **Why not `Display`.** `Accession`'s `Display` renders the compound form
/// (`NG_008939.1(NM_000532.5)`), and that string is both the SPDI's `sequence`
/// field and the key every short-form edit's reference fetch is made against.
/// `MultiFastaProvider::resolve_name` reaches a record for it through the
/// version-strip fallback — `"NG_008939.1(NM_000532.5)".split('.').next()` is
/// `"NG_008939"` — so a **transcript** offset was read out of the **genomic
/// parent**. Measured on the prepared reference:
///
/// ```text
/// get_sequence("NG_008939.1",              191, 197) = CACACA   (the parent)
/// get_sequence("NG_008939.1(NM_000532.5)", 191, 197) = CACACA   <-- same record
/// get_sequence("NM_000532.5",              191, 197) = ACGCCG   <-- the 191's own frame
/// ```
///
/// Splitting the label from the fetch key would not close it: the SPDI's
/// `sequence` field *is* the fetch key for every downstream consumer
/// ([`crate::spdi::apply_to_reference`], and `fetch_window` inside
/// [`crate::spdi::compare_denoted_sequences`]), so a compound label just moves
/// the wrong fetch one hop out. The compound spelling is also not a valid SPDI
/// sequence in the first place — it is HGVS syntax, not an accession, and SPDI's
/// `sequence` must be the accession the position is an offset on.
///
/// **Genomic axes deliberately keep `Display`.** On a `g.`/`m.`/`o.` description
/// the coordinates are the *parent's*, so stripping the wrapper here would name
/// the transcript for a genomic offset — the same defect with the frames
/// swapped. Those paths are untouched.
fn transcript_axis_sequence(accession: &Accession) -> String {
    accession.transcript_accession()
}

/// Convert a non-coding transcript (`n.`) variant to SPDI without consulting
/// a provider. The SPDI is emitted on the transcript accession.
///
/// Returns `MissingReferenceData` for cases that need provider-backed
/// metadata: intronic offsets, downstream (`*N`) positions, and non-positive
/// bases (5' UTR). Use [`hgvs_to_spdi`] with a provider for those.
fn tx_to_spdi_simple(variant: &TxVariant) -> Result<SpdiVariant, ConversionError> {
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_tx = tx_pos_for_simple_path(&variant.loc_edit.location, "n")?;
    let end_tx = tx_end_for_simple_path(&variant.loc_edit.location, "n")?;
    emit_spdi_for_edit(
        transcript_axis_sequence(&variant.accession),
        start_tx,
        end_tx,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        None::<&dyn ReferenceProvider>,
    )
}

/// Convert an RNA (`r.`) variant to SPDI without consulting a provider.
///
/// Identical to [`tx_to_spdi_simple`] in terms of position handling. The
/// edit's deletion/insertion sequences are rewritten with `u`/`U → T` so the
/// output uses the DNA alphabet that SPDI uses by convention (RefSeq stores
/// transcript sequences as DNA even on `NR_*` and `NM_*` accessions).
fn rna_to_spdi_simple(variant: &RnaVariant) -> Result<SpdiVariant, ConversionError> {
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = rna_pos_for_simple_path(&variant.loc_edit.location, "r")?;
    let end_pos = rna_end_for_simple_path(&variant.loc_edit.location, "r")?;
    emit_spdi_for_edit(
        transcript_axis_sequence(&variant.accession),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Rna,
        InsCoordKind::Rna,
        None::<&dyn ReferenceProvider>,
    )
}

/// Convert a genomic variant to SPDI with provider-backed reference fetch.
///
/// Same as [`genome_to_spdi_simple`] for substitution / insertion / identity,
/// but uses the provider to populate the `del` field for short-form
/// `Deletion`, `Duplication`, and `Delins` edits.
fn genome_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &GenomeVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "g")?;
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "g")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        Some(provider),
    )
}

/// Convert a mitochondrial variant to SPDI with provider-backed reference fetch.
///
/// The mito accession is genomic, so the path mirrors
/// [`genome_to_spdi_with_provider`].
///
/// Wraparound variants (start > end, per SVD-WG006) are rejected: SPDI is a
/// single-edit format with no native representation for circular-contig
/// wraparound.
fn mt_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &MtVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "m")?;
    if let (Some(s), Some(e)) = (
        get_start_pos(&variant.loc_edit.location),
        get_end_pos(&variant.loc_edit.location),
    ) {
        if s > e {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "Cannot convert wraparound m. variant to SPDI: SPDI is a single edit and \
                     has no representation for circular-contig wraparound. Variant accession: {}",
                    variant.accession
                ),
            });
        }
    }
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "m")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        Some(provider),
    )
}

/// Convert a circular (`o.`) variant to SPDI (simple conversion).
///
/// Circular accessions follow the same coordinate layout as genomic accessions,
/// so the conversion mirrors the `g.`/`m.` path.
///
/// Wraparound variants (start > end, per SVD-WG006) are rejected: SPDI is a
/// single-edit format with no native representation for circular-contig
/// wraparound.
fn circular_to_spdi_simple(variant: &CircularVariant) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "o")?;
    if let (Some(s), Some(e)) = (
        get_start_pos(&variant.loc_edit.location),
        get_end_pos(&variant.loc_edit.location),
    ) {
        if s > e {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "Cannot convert wraparound o. variant to SPDI: SPDI is a single edit and \
                     has no representation for circular-contig wraparound. Variant accession: {}",
                    variant.accession
                ),
            });
        }
    }
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "o")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        None::<&dyn ReferenceProvider>,
    )
}

/// Convert a circular (`o.`) variant to SPDI with provider-backed reference fetch.
///
/// The circular accession is genomic, so the path mirrors
/// [`genome_to_spdi_with_provider`].
///
/// Wraparound variants (start > end, per SVD-WG006) are rejected: SPDI is a
/// single-edit format with no native representation for circular-contig
/// wraparound.
fn circular_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &CircularVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    reject_unresolvable_genomic_position(&variant.loc_edit.location, "o")?;
    if let (Some(s), Some(e)) = (
        get_start_pos(&variant.loc_edit.location),
        get_end_pos(&variant.loc_edit.location),
    ) {
        if s > e {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "Cannot convert wraparound o. variant to SPDI: SPDI is a single edit and \
                     has no representation for circular-contig wraparound. Variant accession: {}",
                    variant.accession
                ),
            });
        }
    }
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_pos = get_start_pos(&variant.loc_edit.location).ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown start position".to_string(),
        }
    })?;
    let end_pos = resolve_genomic_end_pos(&variant.loc_edit.location, "o")?;
    emit_spdi_for_edit(
        variant.accession.to_string(),
        start_pos,
        end_pos,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        Some(provider),
    )
}

/// Convert a CDS (`c.`) variant to SPDI by resolving CDS coordinates to
/// transcript positions through the supplied provider.
///
/// The resulting SPDI uses the variant's transcript accession (e.g.
/// `NM_000088.3`), matching NCBI Variation Services' convention. Short-form
/// `Deletion` / `Duplication` / `Delins` edits trigger a provider fetch on
/// the transcript accession to populate SPDI's `del` field.
fn cds_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &CdsVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let start_cds = variant.loc_edit.location.start.inner().ok_or_else(|| {
        ConversionError::InvalidPosition {
            description: "cannot convert c. variant with unknown start position".to_string(),
        }
    })?;
    let end_cds = resolve_transcript_end_boundary(&variant.loc_edit.location, "c")?;
    let (start_tx, end_tx) = resolve_cds_to_tx(&variant.accession, start_cds, end_cds, provider)?;
    emit_spdi_for_edit(
        transcript_axis_sequence(&variant.accession),
        start_tx,
        end_tx,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Cds,
        Some(provider),
    )
}

/// Convert an `n.` variant with provider-backed reference fetch and
/// transcript-aware position resolution (intronic offsets, downstream
/// `*N`, non-positive base).
fn tx_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &TxVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let (start_tx, end_tx) = if tx_needs_provider(&variant.loc_edit.location) {
        let start = variant.loc_edit.location.start.inner().ok_or_else(|| {
            ConversionError::InvalidPosition {
                description: "cannot convert n. variant with unknown start position".to_string(),
            }
        })?;
        let end = resolve_transcript_end_boundary(&variant.loc_edit.location, "n")?;
        resolve_tx_to_provider_tx(&variant.accession, start, end, provider)?
    } else {
        resolve_tx_exonic_bounded(&variant.accession, &variant.loc_edit.location, provider)?
    };
    emit_spdi_for_edit(
        transcript_axis_sequence(&variant.accession),
        start_tx,
        end_tx,
        edit,
        AlphabetMode::Dna,
        InsCoordKind::Direct,
        Some(provider),
    )
}

/// Convert an `r.` variant with provider-backed reference fetch. Same
/// coordinate resolution as `n.`; alphabet conversion `u → T` is applied
/// via [`AlphabetMode::Rna`].
fn rna_to_spdi_with_provider<P: ReferenceProvider + ?Sized>(
    variant: &RnaVariant,
    provider: &P,
) -> Result<SpdiVariant, ConversionError> {
    let edit = unwrap_edit(&variant.loc_edit.edit)?;
    let (start_tx, end_tx) = if rna_needs_provider(&variant.loc_edit.location) {
        let start = variant.loc_edit.location.start.inner().ok_or_else(|| {
            ConversionError::InvalidPosition {
                description: "cannot convert r. variant with unknown start position".to_string(),
            }
        })?;
        let end = resolve_transcript_end_boundary(&variant.loc_edit.location, "r")?;
        resolve_rna_to_provider_tx(&variant.accession, start, end, provider)?
    } else {
        resolve_rna_exonic_bounded(&variant.accession, &variant.loc_edit.location, provider)?
    };
    emit_spdi_for_edit(
        transcript_axis_sequence(&variant.accession),
        start_tx,
        end_tx,
        edit,
        AlphabetMode::Rna,
        InsCoordKind::Rna,
        Some(provider),
    )
}

// ===========================================================================
// Shared helpers
// ===========================================================================

/// Whether to rewrite RNA bases (`u/U`) to DNA (`T`) in the emitted SPDI
/// deletion/insertion strings.
///
/// `pub(crate)` for [`crate::spdi::apply`], which reads a key's bases back out
/// of the reference window and so has to fold them in the same convention this
/// module's triples already use.
#[derive(Debug, Clone, Copy)]
pub(crate) enum AlphabetMode {
    Dna,
    Rna,
}

/// Unwrap an edit from `Mu`, returning a clear error if the edit is unknown.
fn unwrap_edit<E>(edit: &crate::hgvs::uncertainty::Mu<E>) -> Result<&E, ConversionError> {
    edit.inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: "cannot convert variant with unknown edit".to_string(),
        })
}

/// Resolve the **end** boundary of a `c.`/`n.`/`r.` interval to the single
/// position SPDI needs, declining when the boundary names none (#1804).
///
/// Two shapes reach here with nothing to resolve, and
/// [`crate::hgvs::interval::UncertainBoundary::inner`] answers `None` for both: a **range** boundary
/// (`(20_30)`, the `Range` variant) and an **unknown** one (`?`, `Mu::Unknown`).
/// Each says "the end is somewhere I am not telling you", and SPDI's end is one
/// exact interbase coordinate — there is no notation for either.
///
/// What every one of the seven call sites did instead was substitute the
/// **start**, which is the one answer worse than refusing: it silently
/// re-describes the variant as ending where it begins. Measured on `main` at
/// `439617c2` against `make_intronic_provider`, `c.10_(20_30)delAAAA` and
/// `c.10_?delAAAA` both converted to `NM_INTRON.1:19:AAAA:` — two descriptions
/// that `parse` and `Display` distinctly, sharing one triple with each other and
/// with any third description of that triple. The short forms are worse still:
/// `c.10_(20_30)del` became `NM_INTRON.1:19:A:`, a **one-base** deletion
/// standing in for one whose end is unknown.
///
/// **This is deliberately not the genomic guard again, and the difference is the
/// whole reason #1795 did not sweep these axes in.**
/// [`reject_unresolvable_genomic_position`] walks *both* endpoints and refuses
/// what it finds *inside* a resolvable one — a `+`/`-` offset, a
/// `pter`/`qter`/`cen` landmark — because neither may appear on a genomic
/// position at all. Here an offset is legitimate: `c.(4185+1_4186-1)_(4357+1_4358-1)del`
/// is well-formed HGVS and is the motivating example on
/// [`crate::hgvs::interval::UncertainBoundary`]. So the offset is not the defect
/// and this resolver never looks at one; what it refuses is the *absence* of a
/// single coordinate, which is a property of the boundary rather than of its
/// contents.
///
/// **The verdict is [`ConversionError::InvalidPosition`], and it is taken from
/// this axis rather than inherited from `g.`** — every one of the seven sites
/// already answers the same question for the **start** side, with `ok_or_else`
/// and exactly that variant ("cannot convert c. variant with unknown start
/// position"). The asymmetry between the two sides *is* the defect, so the end
/// gets what the start has always had.
///
/// Neither of the axis' other two verdicts fits. `MissingReferenceData` means
/// "a well-formed position whose SPDI form needs reference data I do not have",
/// and it invites the caller to supply a provider — but no provider, exon table
/// or genomic projection can resolve `?`, because the uncertainty is in the
/// description rather than in ferro's reference data. `UnrepresentableInSpdi`
/// is nearer but still wrong: it says the *representation* cannot carry an
/// otherwise-determinate position (see [`resolve_cds_to_tx`], [`resolve_tx_pos`],
/// [`require_simple_tx_pos`], whose intronic offsets are exactly that), whereas
/// `?` names no position for any representation to carry.
fn resolve_transcript_end_boundary<'a, T: std::fmt::Display>(
    interval: &'a Interval<T>,
    coord: &str,
) -> Result<&'a T, ConversionError> {
    interval
        .end
        .inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: format!(
                "{coord}. interval end `{}` names no single coordinate: an end that is a range \
                 `(a_b)` or unknown `?` states where the variant ends only approximately, and an \
                 SPDI triple ends at one exact position. Substituting the start would describe a \
                 different variant — one ending where it begins. Give the end a position, or keep \
                 the description in HGVS",
                interval.end
            ),
        })
}

/// Resolve the start position of a `TxInterval` for the simple (no-provider)
/// path. Returns `MissingReferenceData` if the position requires provider data
/// (downstream `*N` or non-positive base), and `UnrepresentableInSpdi` for an
/// intronic offset, which no provider can resolve.
fn tx_pos_for_simple_path(interval: &Interval<TxPos>, coord: &str) -> Result<u64, ConversionError> {
    let start = interval
        .start
        .inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: format!(
                "cannot convert {}. variant with unknown start position",
                coord
            ),
        })?;
    require_simple_tx_pos(start, coord)
}

fn tx_end_for_simple_path(interval: &Interval<TxPos>, coord: &str) -> Result<u64, ConversionError> {
    require_simple_tx_pos(resolve_transcript_end_boundary(interval, coord)?, coord)
}

// No-provider path: with no transcript there is no length to bound against,
// so an exonic position past the 3' end cannot be rejected here (#971). The
// provider-backed path (`hgvs_to_spdi`) does bound; `hgvs_to_spdi_simple`
// callers accept unbounded exonic positions by construction.
fn require_simple_tx_pos(pos: &TxPos, coord: &str) -> Result<u64, ConversionError> {
    // Not `MissingReferenceData`: unlike the two declines below it, this one is
    // not answered by supplying a provider. The provider-backed path refuses an
    // intronic position too (`resolve_tx_pos`), because SPDI has no offset
    // notation — so promising "requires reference provider with exon data" here
    // would send the caller after a provider that cannot help.
    if pos.is_intronic() {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: format!(
                "intronic {}. position cannot be expressed in SPDI without genomic projection; \
                 SPDI is positional and has no offset notation",
                coord
            ),
        });
    }
    if pos.is_downstream() {
        return Err(ConversionError::MissingReferenceData {
            description: format!(
                "downstream {}. position (*N) requires reference provider with transcript length",
                coord
            ),
        });
    }
    if pos.base < 1 {
        return Err(ConversionError::MissingReferenceData {
            description: format!(
                "non-positive {}. position {} requires reference provider with transcript length",
                coord, pos.base
            ),
        });
    }
    Ok(pos.base as u64)
}

fn rna_pos_for_simple_path(
    interval: &Interval<RnaPos>,
    coord: &str,
) -> Result<u64, ConversionError> {
    let start = interval
        .start
        .inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: format!(
                "cannot convert {}. variant with unknown start position",
                coord
            ),
        })?;
    require_simple_rna_pos(start, coord)
}

fn rna_end_for_simple_path(
    interval: &Interval<RnaPos>,
    coord: &str,
) -> Result<u64, ConversionError> {
    require_simple_rna_pos(resolve_transcript_end_boundary(interval, coord)?, coord)
}

// No-provider path: with no transcript there is no length to bound against,
// so an exonic position past the 3' end cannot be rejected here (#971). The
// provider-backed path (`hgvs_to_spdi`) does bound; `hgvs_to_spdi_simple`
// callers accept unbounded exonic positions by construction.
fn require_simple_rna_pos(pos: &RnaPos, coord: &str) -> Result<u64, ConversionError> {
    // See `require_simple_tx_pos`: a representation limit, not a provider gap.
    if pos.is_intronic() {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: format!(
                "intronic {}. position cannot be expressed in SPDI without genomic projection; \
                 SPDI is positional and has no offset notation",
                coord
            ),
        });
    }
    if pos.utr3 {
        return Err(ConversionError::MissingReferenceData {
            description: format!(
                "3' UTR {}. position (*N) requires reference provider with transcript length",
                coord
            ),
        });
    }
    if pos.base < 1 {
        return Err(ConversionError::MissingReferenceData {
            description: format!(
                "non-positive {}. position {} requires reference provider with transcript length",
                coord, pos.base
            ),
        });
    }
    Ok(pos.base as u64)
}

/// True if any endpoint of the interval needs provider data to resolve to a
/// transcript position.
fn tx_needs_provider(interval: &Interval<TxPos>) -> bool {
    let needs = |p: &TxPos| p.is_intronic() || p.is_downstream() || p.base < 1;
    interval.start.inner().is_some_and(needs) || interval.end.inner().is_some_and(needs)
}

fn rna_needs_provider(interval: &Interval<RnaPos>) -> bool {
    let needs = |p: &RnaPos| p.is_intronic() || p.utr3 || p.base < 1;
    interval.start.inner().is_some_and(needs) || interval.end.inner().is_some_and(needs)
}

/// Resolve a CDS-position pair to 1-based transcript positions using the
/// provider's transcript metadata.
///
/// Intronic c. positions (e.g. `c.100+5`) are rejected: SPDI is positional
/// and has no offset notation, so an intronic CDS variant cannot be expressed
/// on the transcript accession without first projecting to genomic coords.
/// That projection is intentionally out of scope for this entry point —
/// callers needing it can use the genomic conversion path explicitly.
///
/// That rejection is [`ConversionError::UnrepresentableInSpdi`] and is raised
/// **before the provider is consulted at all**, which is why it must not be
/// `MissingReferenceData`: no amount of reference data changes the answer, and
/// a consumer classifying the error would otherwise read a decidable case as
/// "could not tell".
fn resolve_cds_to_tx<P: ReferenceProvider + ?Sized>(
    accession: &Accession,
    start: &CdsPos,
    end: &CdsPos,
    provider: &P,
) -> Result<(u64, u64), ConversionError> {
    if start.is_intronic() || end.is_intronic() {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: "intronic c. positions cannot be expressed in SPDI without genomic \
                          projection; SPDI is positional and has no offset notation"
                .to_string(),
        });
    }
    let tx_id = accession.transcript_accession();
    let transcript =
        provider
            .get_transcript(&tx_id)
            .map_err(|e| ConversionError::MissingReferenceData {
                description: format!("could not load transcript {}: {}", tx_id, e),
            })?;
    let mapper = CoordinateMapper::new(&transcript);
    let s = mapper
        .cds_to_tx(start)
        .map_err(|e| ConversionError::MissingReferenceData {
            description: format!("could not resolve {} to transcript position: {}", start, e),
        })?;
    let e = mapper
        .cds_to_tx(end)
        .map_err(|e| ConversionError::MissingReferenceData {
            description: format!("could not resolve {} to transcript position: {}", end, e),
        })?;
    // Bound both endpoints against the transcript length: reject a position that
    // maps past the 3' end, not just below base 1. #962 did this for c.*N (3'UTR);
    // #971 extends it to plain exonic c.N, which cds_to_tx can also map off-sequence
    // (e.g. c.99999 -> tx cds_start-1+99999). Keeps c.N / r.N / n.N symmetric.
    let tx_len = transcript.sequence_length();
    let s_u = ensure_tx_in_bounds(s.base, tx_len, "c", start)?;
    let e_u = ensure_tx_in_bounds(e.base, tx_len, "c", end)?;
    Ok((s_u, e_u))
}

/// Resolve an `n.` (TxPos) pair to 1-based transcript positions, including
/// intronic and downstream forms, using the provider.
fn resolve_tx_to_provider_tx<P: ReferenceProvider + ?Sized>(
    accession: &Accession,
    start: &TxPos,
    end: &TxPos,
    provider: &P,
) -> Result<(u64, u64), ConversionError> {
    let tx_id = accession.transcript_accession();
    let transcript =
        provider
            .get_transcript(&tx_id)
            .map_err(|e| ConversionError::MissingReferenceData {
                description: format!("could not load transcript {}: {}", tx_id, e),
            })?;
    let s = resolve_tx_pos(start, &transcript)?;
    let e = resolve_tx_pos(end, &transcript)?;
    Ok((s, e))
}

/// Best-effort upper-bounding of a plain exonic `n.` interval (positive base,
/// non-intronic, non-downstream). When the provider supplies the transcript,
/// each endpoint is bounded against its length via [`resolve_tx_pos`] (#971);
/// if the transcript cannot be loaded, fall back to the unbounded simple-path
/// value so a provider that lacks it still resolves (no regression).
///
/// Only a `MissingReferenceData` error (transcript unavailable) triggers the
/// fallback; an over-length position surfaces as `InvalidPosition` from the
/// bound and is propagated, not swallowed.
fn resolve_tx_exonic_bounded<P: ReferenceProvider + ?Sized>(
    accession: &Accession,
    interval: &Interval<TxPos>,
    provider: &P,
) -> Result<(u64, u64), ConversionError> {
    let start = interval
        .start
        .inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: "cannot convert n. variant with unknown start position".to_string(),
        })?;
    let end = resolve_transcript_end_boundary(interval, "n")?;
    match resolve_tx_to_provider_tx(accession, start, end, provider) {
        Ok(pair) => Ok(pair),
        Err(ConversionError::MissingReferenceData { .. }) => {
            let s = tx_pos_for_simple_path(interval, "n")?;
            let e = tx_end_for_simple_path(interval, "n")?;
            Ok((s, e))
        }
        Err(e) => Err(e),
    }
}

/// Best-effort upper-bounding of a plain exonic `r.` interval, mirroring
/// [`resolve_tx_exonic_bounded`]: bound against the transcript length when the
/// provider supplies it (#971), else fall back to the unbounded simple-path
/// value. Only `MissingReferenceData` (transcript unavailable) triggers the
/// fallback; an over-length position propagates as `InvalidPosition`.
fn resolve_rna_exonic_bounded<P: ReferenceProvider + ?Sized>(
    accession: &Accession,
    interval: &Interval<RnaPos>,
    provider: &P,
) -> Result<(u64, u64), ConversionError> {
    let start = interval
        .start
        .inner()
        .ok_or_else(|| ConversionError::InvalidPosition {
            description: "cannot convert r. variant with unknown start position".to_string(),
        })?;
    let end = resolve_transcript_end_boundary(interval, "r")?;
    match resolve_rna_to_provider_tx(accession, start, end, provider) {
        Ok(pair) => Ok(pair),
        Err(ConversionError::MissingReferenceData { .. }) => {
            let s = rna_pos_for_simple_path(interval, "r")?;
            let e = rna_end_for_simple_path(interval, "r")?;
            Ok((s, e))
        }
        Err(e) => Err(e),
    }
}

fn resolve_rna_to_provider_tx<P: ReferenceProvider + ?Sized>(
    accession: &Accession,
    start: &RnaPos,
    end: &RnaPos,
    provider: &P,
) -> Result<(u64, u64), ConversionError> {
    let tx_id = accession.transcript_accession();
    let transcript =
        provider
            .get_transcript(&tx_id)
            .map_err(|e| ConversionError::MissingReferenceData {
                description: format!("could not load transcript {}: {}", tx_id, e),
            })?;
    let s = resolve_rna_pos(start, &transcript)?;
    let e = resolve_rna_pos(end, &transcript)?;
    Ok((s, e))
}

/// Resolve a single `TxPos` to a 1-based transcript position. Intronic and
/// downstream (`n.*N`) positions are rejected because they have no valid
/// SPDI representation on the transcript accession; an exonic position past
/// the transcript's 3' end is also rejected (#971).
fn resolve_tx_pos(pos: &TxPos, transcript: &Transcript) -> Result<u64, ConversionError> {
    // SPDI is positional and has no offset notation, so intronic n. positions
    // cannot be expressed without genomic projection. Match the sibling
    // `resolve_rna_pos` (and the simple-path helpers) by emitting
    // `UnrepresentableInSpdi` here: the answer is decided by the position's own
    // spelling, and no provider changes it.
    if pos.is_intronic() {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: format!(
                "intronic n.{} cannot be expressed in SPDI without genomic projection; \
                 SPDI is positional and has no offset notation",
                pos
            ),
        });
    }
    // n. has no CDS anchor, so `n.*N` is N bases past the transcript end —
    // an off-sequence position on the transcript accession. Reject until
    // genomic projection is wired in; emitting SPDI at `tx_len + N` would
    // produce a coordinate that does not exist on the accession.
    if pos.is_downstream() {
        return Err(ConversionError::InvalidPosition {
            description: format!(
                "downstream n.{} cannot be expressed in SPDI on the transcript accession \
                 without genomic projection",
                pos
            ),
        });
    }
    // Exonic n.N: bound against the transcript length so an over-length position
    // (n.99999 on a 40-base transcript) declines instead of emitting an
    // off-sequence SPDI coordinate (#971), mirroring the c.*N / r.*N bound (#962).
    ensure_tx_in_bounds(pos.base, transcript.sequence_length(), "n", pos)
}

fn resolve_rna_pos(pos: &RnaPos, transcript: &Transcript) -> Result<u64, ConversionError> {
    // As in `resolve_tx_pos`: a representation limit, read off the spelling.
    if pos.is_intronic() {
        return Err(ConversionError::UnrepresentableInSpdi {
            description: format!(
                "intronic r.{} cannot be expressed in SPDI without genomic projection; \
                 SPDI is positional and has no offset notation",
                pos
            ),
        });
    }
    if pos.utr3 {
        // r.*N is the Nth base of the 3' UTR — anchored after the stop codon,
        // so r.*1 sits at the base immediately after the last CDS position, not
        // at `tx_len + 1` (one past the entire mRNA). For non-coding transcripts
        // r.*N has no meaning; surface `MissingReferenceData` rather than fall
        // back to `tx_len` (#390 item 2).
        if pos.base < 1 {
            return Err(ConversionError::InvalidPosition {
                description: format!("3' UTR position *{} must be >= 1", pos.base),
            });
        }
        // r.*N and c.*N denote the same transcript position, so resolve r.*N
        // through the same `CoordinateMapper::cds_to_tx` the c.*N path
        // (`resolve_cds_to_tx`) uses, rather than open-coding `cds_end + base`
        // here (#390-follow-up / #944). One conversion, one place: the two
        // arms cannot drift apart, which is the property those issues are
        // about. Since #1619 that conversion is the flat sequence-axis shift —
        // `c.*N` counts the transcript's own bases, including any the exon
        // table does not cover — so the two spellings agree by construction.
        // Requires a CDS end — non-coding transcripts have no 3'UTR anchor.
        if transcript.cds_end.is_none() {
            return Err(ConversionError::MissingReferenceData {
                description: format!(
                    "r.*{} requires a CDS end on the transcript; non-coding \
                     transcripts have no 3'UTR anchor",
                    pos.base
                ),
            });
        }
        let mapper = CoordinateMapper::new(transcript);
        let tx = mapper.cds_to_tx(&CdsPos::utr3(pos.base)).map_err(|e| {
            ConversionError::MissingReferenceData {
                description: format!(
                    "could not resolve r.*{} to transcript position: {}",
                    pos.base, e
                ),
            }
        })?;
        return ensure_tx_in_bounds(tx.base, transcript.sequence_length(), "r", pos);
    }
    if pos.is_5utr() {
        // r.-N is the Nth base of the 5' UTR — numbered upstream from the start
        // codon, exactly mirroring c.-N (numbering.md:58/61: RNA numbering
        // follows the coding DNA reference, which includes c.-N). Resolve it
        // through the same `CoordinateMapper::cds_to_tx` the c.-N path
        // (`resolve_cds_to_tx`) uses — via the equivalent `CdsPos` with base < 1 —
        // so r.-N and c.-N always land at the same transcript/SPDI position.
        // Routing both through one conversion is what guarantees that; since
        // #1619 the conversion itself is the flat `cds_start - N` shift, on the
        // transcript's own bases rather than on the exon table. Requires a CDS
        // start — non-coding transcripts have no 5'UTR anchor.
        if transcript.cds_start.is_none() {
            return Err(ConversionError::MissingReferenceData {
                description: format!(
                    "r.{} requires a CDS start on the transcript; non-coding \
                     transcripts have no 5'UTR anchor",
                    pos.base
                ),
            });
        }
        let mapper = CoordinateMapper::new(transcript);
        let tx = mapper.cds_to_tx(&CdsPos::new(pos.base)).map_err(|e| {
            ConversionError::MissingReferenceData {
                description: format!(
                    "could not resolve r.{} to transcript position: {}",
                    pos.base, e
                ),
            }
        })?;
        return ensure_positive_tx(tx.base, "r", pos);
    }
    // Exonic r.N. On a CODING transcript r. numbering is CDS-relative (#469):
    // r.N denotes the same base as c.N (see `cds_pos_to_rna` in project/rna.rs),
    // so resolve it through the same `CoordinateMapper::cds_to_tx` exactly
    // like c.N and like the r.-N / r.*N branches above — otherwise r.N would be
    // treated as transcript-absolute and disagree with c.N by (cds_start - 1).
    // A NON-coding (NR_) transcript has no CDS anchor, so r.N IS the transcript
    // position directly. Either way, bound against the transcript length (#971).
    if transcript.cds_start.is_some() {
        // Resolving a coding r.N CDS-relative needs a CDS end (`cds_to_tx`
        // requires both anchors). A coding transcript missing its
        // CDS end is malformed/partial annotation: decline with
        // `InvalidPosition` (which propagates past the
        // `resolve_rna_exonic_bounded` `MissingReferenceData` fallback) rather
        // than silently resolving r.N transcript-absolute and unbounded — the
        // same "loaded but inexpressible" treatment `resolve_tx_pos` gives a
        // downstream n.*N. Mirrors the cds_end guard on the r.*N branch above.
        if transcript.cds_end.is_none() {
            return Err(ConversionError::InvalidPosition {
                description: format!(
                    "r.{} on a coding transcript requires a CDS end to resolve \
                     CDS-relative; the transcript has a CDS start but no CDS end",
                    pos.base
                ),
            });
        }
        let mapper = CoordinateMapper::new(transcript);
        let tx = mapper.cds_to_tx(&CdsPos::new(pos.base)).map_err(|e| {
            ConversionError::MissingReferenceData {
                description: format!(
                    "could not resolve r.{} to transcript position: {}",
                    pos.base, e
                ),
            }
        })?;
        return ensure_tx_in_bounds(tx.base, transcript.sequence_length(), "r", pos);
    }
    ensure_tx_in_bounds(pos.base, transcript.sequence_length(), "r", pos)
}

fn ensure_positive_tx<P: std::fmt::Display>(
    base: i64,
    coord: &str,
    pos: P,
) -> Result<u64, ConversionError> {
    if base < 1 {
        return Err(ConversionError::InvalidPosition {
            description: format!(
                "transcript position from {}. coordinate {} resolves to a non-positive base ({})",
                coord, pos, base
            ),
        });
    }
    Ok(base as u64)
}

/// Like [`ensure_positive_tx`], but also rejects a resolved 1-based transcript
/// position that falls *past the transcript's 3' end* (`base > tx_len`).
///
/// A `*N` position numbered beyond the last transcript base — e.g. `r.*99999` /
/// `c.*99999` on a short transcript — maps to a coordinate that does not exist on
/// the accession. `ensure_positive_tx` guards only the lower bound, so without
/// this the resolver would emit an off-sequence SPDI position (#962). `tx_len` is
/// the transcript length in mRNA bases ([`Transcript::sequence_length`]). Applied
/// at the `*N` (3'UTR) resolution sites — `r.*N` in `resolve_rna_pos` and `c.*N`
/// in `resolve_cds_to_tx` — where a position can be numbered past the last
/// transcript base, and at the exonic resolution sites — `n.N` in
/// `resolve_tx_pos`, the exonic tail of `r.N` in `resolve_rna_pos`, and both
/// arms of `c.N` in `resolve_cds_to_tx` — where an over-length position (e.g.
/// `c.99999` on a short transcript) can likewise map past the 3' end (#971).
fn ensure_tx_in_bounds<P: std::fmt::Display + Copy>(
    base: i64,
    tx_len: u64,
    coord: &str,
    pos: P,
) -> Result<u64, ConversionError> {
    let one_based = ensure_positive_tx(base, coord, pos)?;
    if one_based > tx_len {
        return Err(ConversionError::InvalidPosition {
            description: format!(
                "transcript position from {}. coordinate {} resolves to base {} past the \
                 transcript 3' end (length {})",
                coord, pos, one_based, tx_len
            ),
        });
    }
    Ok(one_based)
}

/// Apply edit-specific position arithmetic and emit the SPDI variant.
///
/// `start_one_based` and `end_one_based` are 1-based positions on the SPDI
/// accession (genomic for `g.`/`m.`, transcript for `c.`/`n.`/`r.`).
///
/// # Position convention per edit
///
/// SPDI's `position` field is 0-based. For substitution / deletion /
/// delins (edits that reference specific bases) the SPDI position
/// equals `start_one_based - 1` (computed once at the top of the
/// function as `spdi_pos`). For **insertion** and **duplication** the
/// SPDI position is *interbase* — position N is the boundary AFTER
/// 1-based base N — so the Insertion arm uses `start_one_based`
/// directly and the Duplication arm uses `end_one_based` directly
/// (#390 item 1). The top-of-function `spdi_pos` is unused in those
/// two arms.
///
/// # Provider behavior
///
/// When `provider` is `Some` and the edit is a short-form deletion,
/// duplication, delins, or identity (i.e. lacks an explicit deleted
/// sequence), the reference bases for `[start_one_based, end_one_based]` are
/// fetched via the provider so SPDI's mandatory `del` field can be populated.
/// When `provider` is `None`, those cases return
/// [`ConversionError::MissingReferenceData`].
///
/// A **whole-entity** identity (`g.=`) is the one exception: it names no
/// interval, so it returns [`ConversionError::UnsupportedEditType`] rather
/// than a triple at an arbitrary position.
fn emit_spdi_for_edit<P>(
    sequence: String,
    start_one_based: u64,
    end_one_based: u64,
    edit: &NaEdit,
    alphabet: AlphabetMode,
    ins_coords: InsCoordKind,
    provider: Option<&P>,
) -> Result<SpdiVariant, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let hgvs_pos_ob =
        OneBasedPos::try_new(start_one_based).ok_or_else(|| ConversionError::InvalidPosition {
            description: "position 0 is not valid in HGVS".to_string(),
        })?;
    let spdi_pos_zb: ZeroBasedPos = hgvs_pos_ob.to_zero_based();
    let spdi_pos = spdi_pos_zb.value();

    match edit {
        NaEdit::Substitution {
            reference,
            alternative,
        } => Ok(SpdiVariant::new(
            sequence,
            spdi_pos,
            apply_alphabet(&reference.to_string(), alphabet),
            apply_alphabet(&alternative.to_string(), alphabet),
        )),
        NaEdit::Insertion { sequence: inserted } => {
            // An inserted sequence reaches SPDI when its exact bases are known.
            // Three shapes are handled here: a literal; a same-reference range
            // insert (`ins50_57`, `ins50_57inv`), resolved from the reference
            // exactly as `del`/`dup` resolve their omitted bases; and an exact
            // tandem-repeat insert (`insA[10]`, `insAT[3]`), expanded from its
            // spelled unit exactly as the short-form `Repeat` arm expands its
            // own. The fallback rejects everything else, which is now uniformly
            // shapes whose bases are genuinely undetermined: `Count` (`ins10`),
            // `Range` (`ins(10_20)`), `Uncertain` (`ins(?)`), an uncertain or
            // range repeat count (`insA[10_15]`), and named/external references
            // SPDI cannot dereference.
            let ins_str = if let Some(resolved) =
                resolve_position_range_insert(inserted, &sequence, alphabet, ins_coords, provider)?
            {
                resolved
            } else if let Some(resolved) = resolve_exact_repeat_insert(inserted, alphabet)? {
                resolved
            } else if let Some(resolved) =
                resolve_complex_insert(inserted, &sequence, alphabet, ins_coords, provider)?
            {
                resolved
            } else {
                let literal = inserted_sequence_to_string(inserted).ok_or_else(|| {
                    ConversionError::MissingReferenceData {
                        description: "insertion sequence is neither a literal sequence, a \
                                      same-reference position range, nor an exact tandem repeat; \
                                      this shape is not yet encodable as SPDI"
                            .to_string(),
                    }
                })?;
                apply_alphabet(&literal, alphabet)
            };
            // SPDI is 0-based interbase: position N is the boundary
            // AFTER 1-based base N (equivalently between 1-based bases
            // N and N+1). For HGVS `g.{start}_{start+1}ins{seq}` the
            // matching SPDI position is `start_one_based` directly
            // (NOT the -1 conversion used for substitution/deletion,
            // which references a specific base). Closes #390 item 1.
            Ok(SpdiVariant::new(sequence, start_one_based, "", ins_str))
        }
        NaEdit::Duplication {
            sequence: dup_seq, ..
        } => {
            let dup_str = match dup_seq {
                Some(seq) => sequence_to_string(seq),
                None => match provider {
                    Some(p) => fetch_reference_bases(p, &sequence, start_one_based, end_one_based)?,
                    None => {
                        return Err(unspelled_bases_error(
                            UnspelledBases::Duplicated,
                            start_one_based,
                            end_one_based,
                        ));
                    }
                },
            };
            // SPDI encodes a duplication as an insertion immediately
            // after the duplicated region. With the corrected
            // interbase convention (see Insertion arm above), that
            // position is the 1-based end of the duplicated region
            // (`end_one_based`) directly. Closes #390 item 1.
            Ok(SpdiVariant::new(
                sequence,
                end_one_based,
                "",
                apply_alphabet(&dup_str, alphabet),
            ))
        }
        NaEdit::Deletion {
            sequence: del_seq, ..
        } => {
            let del_str = match del_seq {
                Some(seq) => sequence_to_string(seq),
                None => match provider {
                    Some(p) => fetch_reference_bases(p, &sequence, start_one_based, end_one_based)?,
                    None => {
                        return Err(unspelled_bases_error(
                            UnspelledBases::Deleted,
                            start_one_based,
                            end_one_based,
                        ));
                    }
                },
            };
            Ok(SpdiVariant::new(
                sequence,
                spdi_pos,
                apply_alphabet(&del_str, alphabet),
                "",
            ))
        }
        NaEdit::Delins {
            sequence: ins_seq,
            deleted,
            deleted_length: _,
            substitution_reference: None,
        } => {
            // Closes #394 item 3. An inserted sequence reaches SPDI when its
            // exact bases are known. Three shapes are handled: a literal; a
            // same-reference position-range insert (`delins50_57`,
            // `delins50_57inv`), resolved from the reference exactly as
            // `del`/`dup` resolve their omitted bases; and an exact tandem-repeat
            // insert (`delinsA[10]`, `delinsAT[3]`), expanded from its spelled
            // unit exactly as the short-form `Repeat` arm expands its own. The
            // fallback rejects everything else, which is now uniformly shapes
            // whose bases are genuinely undetermined (`Count` `ins10`, `Range`
            // `ins(10_20)`, `Uncertain`, an uncertain or range repeat count, and
            // named/external references SPDI cannot dereference), and declines as
            // `UnsupportedEditType` — matching the sibling arms.
            let ins_str = if let Some(resolved) =
                resolve_position_range_insert(ins_seq, &sequence, alphabet, ins_coords, provider)?
            {
                resolved
            } else if let Some(resolved) = resolve_exact_repeat_insert(ins_seq, alphabet)? {
                resolved
            } else if let Some(resolved) =
                resolve_complex_insert(ins_seq, &sequence, alphabet, ins_coords, provider)?
            {
                resolved
            } else {
                let literal = inserted_sequence_to_string(ins_seq).ok_or_else(|| {
                    ConversionError::UnsupportedEditType {
                        description: "delins inserted sequence is neither a literal sequence, a \
                                      same-reference position range, nor an exact tandem repeat; \
                                      this shape is not yet encodable as SPDI"
                            .to_string(),
                    }
                })?;
                apply_alphabet(&literal, alphabet)
            };
            let del_str = match deleted {
                Some(seq) => sequence_to_string(seq),
                None => match provider {
                    Some(p) => fetch_reference_bases(p, &sequence, start_one_based, end_one_based)?,
                    None => {
                        return Err(unspelled_bases_error(
                            UnspelledBases::DeletedInDelins,
                            start_one_based,
                            end_one_based,
                        ));
                    }
                },
            };
            Ok(SpdiVariant::new(
                sequence,
                spdi_pos,
                apply_alphabet(&del_str, alphabet),
                ins_str,
            ))
        }
        NaEdit::Identity {
            sequence: id_seq,
            whole_entity,
        } => {
            // An identity claims the bases it names, so its triple must span
            // them: `g.263=` is `262:A:A`, not the zero-width `262::`. A
            // zero-width triple is not merely less informative, it *aliases an
            // insertion junction* — put `g.[261_262dup;263=]` through it and
            // both members land on interbase 262, which is indistinguishable
            // from two insertions competing for one interbase.
            //
            // When the input does not spell the base, fetch it, exactly as the
            // Deletion / Delins / Inversion arms do for their own omitted
            // sequences.
            let ref_base = match id_seq {
                Some(seq) => sequence_to_string(seq),
                // `g.=` asserts the whole reference is unchanged and names no
                // interval, so there is no position SPDI could honestly carry.
                // Emitting `0::` looks harmless but round-trips through
                // `spdi_to_hgvs` as `g.1=`, narrowing a statement about the
                // whole sequence to one about base 1. Decline instead, as this
                // module does for every other shape SPDI cannot encode.
                None if *whole_entity => {
                    return Err(ConversionError::UnsupportedEditType {
                        description: "a whole-entity identity (`=`) asserts the entire \
                                      reference is unchanged and names no interval; SPDI \
                                      has no representation for it"
                            .to_string(),
                    });
                }
                None => match provider {
                    Some(p) => fetch_reference_bases(p, &sequence, start_one_based, end_one_based)?,
                    None => {
                        return Err(unspelled_bases_error(
                            UnspelledBases::Unchanged,
                            start_one_based,
                            end_one_based,
                        ));
                    }
                },
            };
            let ref_base = apply_alphabet(&ref_base, alphabet);
            Ok(SpdiVariant::new(
                sequence,
                spdi_pos,
                ref_base.clone(),
                ref_base,
            ))
        }
        NaEdit::Inversion {
            sequence: inv_seq, ..
        } => {
            // SPDI has no native inv; the standard mapping is delins where
            // ins is the reverse-complement of the deleted reference span.
            let del_raw = match inv_seq {
                Some(seq) => sequence_to_string(seq),
                None => match provider {
                    Some(p) => fetch_reference_bases(p, &sequence, start_one_based, end_one_based)?,
                    None => {
                        return Err(unspelled_bases_error(
                            UnspelledBases::Inverted,
                            start_one_based,
                            end_one_based,
                        ));
                    }
                },
            };
            let del_str = apply_alphabet(&del_raw, alphabet);
            let ins_str = reverse_complement(&del_str);
            Ok(SpdiVariant::new(sequence, spdi_pos, del_str, ins_str))
        }
        NaEdit::Repeat {
            sequence: unit_seq,
            count,
            additional_counts,
            trailing,
        } => {
            // SPDI has no native repeat; expand to delins where del is the
            // reference repeat tract and ins is the unit repeated `count`
            // times. Only an explicit unit and exact count are representable.
            if !additional_counts.is_empty() {
                return Err(ConversionError::UnsupportedEditType {
                    description:
                        "genotype-style repeat (multiple counts) cannot be expressed as a single SPDI; emit each allele separately"
                            .to_string(),
                });
            }
            if trailing.is_some() {
                return Err(ConversionError::UnsupportedEditType {
                    description: "repeat with trailing sequence cannot be represented in SPDI"
                        .to_string(),
                });
            }
            let unit = unit_seq
                .as_ref()
                .ok_or_else(|| ConversionError::MissingReferenceData {
                    description:
                        "repeat unit sequence not provided; cannot expand into SPDI delins"
                            .to_string(),
                })?;
            let n_post = match count {
                RepeatCount::Exact(n) => *n as usize,
                // Range, UncertainRange, MinUncertain, MaxUncertain, Unknown:
                // no single expanded ins-string exists, so SPDI cannot encode.
                _ => {
                    return Err(ConversionError::UnsupportedEditType {
                        description:
                            "uncertain or range repeat counts cannot be represented in SPDI"
                                .to_string(),
                    });
                }
            };
            let unit_str = apply_alphabet(&sequence_to_string(unit), alphabet);
            // An `N`-unit repeat (`g.pos_posN[n]`) names a length, not bases —
            // the same undetermined content the inserted-sequence repeat path
            // refuses. Decline before consulting the reference, on the same
            // grounds as `insN[n]` (ruling `spdi-n-unit-repeat-refusal`, #1975).
            refuse_undetermined_repeat_unit(&unit_str)?;
            // Bound the expanded ins-string before allocating. The count is
            // user-controlled (u64), so `unit_str.repeat(n_post)` can be
            // forced to allocate gigabytes from a single short input.
            let expansion_bases = unit_str.len().checked_mul(n_post).ok_or_else(|| {
                ConversionError::UnsupportedEditType {
                    description: format!(
                        "repeat expansion {} x {} overflows usize",
                        unit_str.len(),
                        n_post
                    ),
                }
            })?;
            if expansion_bases > MAX_REPEAT_EXPANSION_BASES {
                return Err(ConversionError::UnsupportedEditType {
                    description: format!(
                        "repeat expansion {} bases exceeds SPDI ins-string cap of {} bases",
                        expansion_bases, MAX_REPEAT_EXPANSION_BASES
                    ),
                });
            }
            // A single-position anchor names the tract's *start*, not a
            // one-base span, so widen it to the physical run before fetching
            // (#1431).
            //
            // The spec presents the two spellings as two formats of one
            // variant — "a Community Consultation proposal is being prepared
            // which will suggest to allow only the format where the **entire
            // range** of the repeated sequence is indicated; so
            // `g.123_191CAG[23]`, **not** `g.123CAG[23]`"
            // (`DNA/repeated.md`) — and `123_191` is 69 bases, the whole
            // 23-copy tract. Reading the anchor as a one-base span instead
            // made the two disagree: on a 3-base `A` tract at 263,
            // `g.263A[7]` came out as `262:A:AAAAAAA`, which denotes **nine**
            // `A`s once the two untouched tract bases are counted, while
            // `g.263_265A[7]` correctly denotes seven.
            //
            // The one-base reading also does not survive a multi-base unit at
            // all: `g.263CAG[5]` fetched a single base and died on the
            // divisibility check below ("length 1 is not a multiple of unit
            // length 3"), so the spec's own start-only format was unusable for
            // every unit the spec actually illustrates it with.
            //
            // This is the reading `merge::lowered_repeat` already documents —
            // "a single-position anchor (`e == s`) names only the tract's
            // start and means 'the whole run becomes N', so it absorbs
            // nothing" — so widening here makes the two sites agree rather
            // than introducing a third answer.
            let (del_start, del_end, span_origin) = match provider {
                Some(p) if start_one_based == end_one_based => resolve_repeat_tract_span(
                    p,
                    &sequence,
                    start_one_based,
                    unit_str.as_bytes(),
                    alphabet,
                )?,
                // An explicit range is the caller's own span, so a decline may
                // quote it verbatim.
                _ => (start_one_based, end_one_based, RepeatSpanOrigin::Tract),
            };
            let spdi_pos = del_start - 1;
            let del_str = match provider {
                Some(p) => {
                    fetch_normalized_reference_bases(p, &sequence, del_start, del_end, alphabet)?
                }
                None => {
                    return Err(unspelled_bases_error(
                        UnspelledBases::RepeatTract,
                        start_one_based,
                        end_one_based,
                    ));
                }
            };
            // Two things must hold for the span to be the declared repeat: the
            // HGVS recommendations require an integer number of units
            // (`inversion`-style nonsense otherwise), and a divisible length is
            // necessary but not sufficient — `ATGCAT` is length 6 and is not
            // `AT[3]`.
            //
            // **Both are judged before either is reported**, because the two
            // failures share one diagnostic decision. After a failed tract
            // search `del_start`/`del_end` are this module's unit-wide fallback
            // rather than anything the caller wrote, and *either* check can be
            // the one that trips on it: near the 3' end the fallback is clamped
            // inside the contig, so a multi-base unit leaves a short span that
            // fails divisibility first. Reporting that span names coordinates
            // nobody supplied — the exact defect #1492 is about — so the origin
            // decides the message and the checks only decide *whether* there is
            // one.
            let divisible = !unit_str.is_empty() && del_str.len().is_multiple_of(unit_str.len());
            let matches_unit =
                divisible && del_str == unit_str.repeat(del_str.len() / unit_str.len());
            if !matches_unit {
                return Err(ConversionError::InvalidPosition {
                    description: match span_origin {
                        // The span is the fallback, not the caller's. Name the
                        // anchor and the real fault: no run begins there.
                        RepeatSpanOrigin::NoRunAtAnchor => format!(
                            "no {unit} repeat is anchored at {seq}:{anchor}: the reference \
                             there is not a run of {unit}. A single-position anchor names the \
                             *first base* of the tract, so check the run's start, or spell the \
                             whole range explicitly (`g.<start>_<end>{unit}[n]`).",
                            unit = unit_str,
                            seq = sequence,
                            anchor = start_one_based,
                        ),
                        // The span is one the caller wrote or the search chose,
                        // so quoting it is honest.
                        _ if !divisible => format!(
                            "repeat span {}:{}-{} length {} is not a multiple of unit length {}",
                            sequence,
                            del_start,
                            del_end,
                            del_str.len(),
                            unit_str.len()
                        ),
                        _ => format!(
                            "repeat span {}:{}-{} does not match repeat unit {}",
                            sequence, del_start, del_end, unit_str
                        ),
                    },
                });
            }
            let ins_str = unit_str.repeat(n_post);
            Ok(SpdiVariant::new(sequence, spdi_pos, del_str, ins_str))
        }
        NaEdit::CopyNumber { .. } => Err(ConversionError::UnsupportedEditType {
            description: "copy number variants cannot be represented in SPDI format".to_string(),
        }),
        NaEdit::Conversion { .. } => Err(ConversionError::UnsupportedEditType {
            description: "conversion variants cannot be represented in SPDI format".to_string(),
        }),
        _ => Err(ConversionError::UnsupportedEditType {
            description: format!("unsupported edit type: {:?}", edit),
        }),
    }
}

/// The edit shapes whose SPDI form needs reference bases the description did
/// not spell out. Each names what is unknown and how the caller could spell it.
///
/// Exists so the six arms of [`hgvs_to_spdi`] that hit this wall decline in one
/// voice. They previously carried six hand-written strings, none of which named
/// the interval that could not be resolved or either way out, and one of which
/// (`Delins`) had drifted into a different sentence shape than its siblings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnspelledBases {
    Duplicated,
    Deleted,
    DeletedInDelins,
    Unchanged,
    Inverted,
    /// A repeat's pre-expansion tract. The odd one out: see
    /// [`Self::spelled_example`].
    RepeatTract,
}

impl UnspelledBases {
    /// How to describe the missing bases: `"the {} bases at 10..=12"`.
    fn adjective(self) -> &'static str {
        match self {
            Self::Duplicated => "duplicated",
            Self::Deleted | Self::DeletedInDelins => "deleted",
            Self::Unchanged => "unchanged",
            Self::Inverted => "inverted",
            Self::RepeatTract => "pre-expansion repeat-tract",
        }
    }

    /// A spelled-out form of this shape, offered as the example in the message —
    /// or `None` where the description has no way to carry the bases.
    ///
    /// `RepeatTract` is that case, and it is why this returns an `Option`. The
    /// other five arms all read an optional sequence off the edit first and only
    /// consult the provider when it is absent, so "spell it" is genuinely a way
    /// out. The repeat arm has no such field to fill: the notation states the
    /// *unit* (`g.10AC[3]`), never the span the tract currently occupies, so the
    /// provider is the only route and suggesting otherwise would send the caller
    /// after a description they cannot write.
    ///
    /// Every `Some` here **must parse** — an error message that suggests a
    /// description ferro would itself reject is worse than one that suggests
    /// nothing. `spelled_examples_are_parseable` holds them to that.
    fn spelled_example(self) -> Option<&'static str> {
        match self {
            Self::Duplicated => Some("g.10_12dupACG"),
            Self::Deleted => Some("g.10_12delACG"),
            Self::DeletedInDelins => Some("g.10_12delACGinsT"),
            Self::Unchanged => Some("g.10A="),
            Self::Inverted => Some("g.10_12invACG"),
            Self::RepeatTract => None,
        }
    }
}

/// Decline a conversion that needs bases the description left implicit.
///
/// Names the interval and every remedy that actually exists, because a caller who
/// hits this has one or two ways forward — spell the bases in the description
/// where the notation allows it, or pass a provider that can look them up — and
/// neither is guessable from "reference data needed".
fn unspelled_bases_error(
    what: UnspelledBases,
    start_one_based: u64,
    end_one_based: u64,
) -> ConversionError {
    let remedy = match what.spelled_example() {
        Some(example) => format!(
            "Spell them in the description (e.g. `{example}`) or convert with a reference provider."
        ),
        None => "Convert with a reference provider: the repeat notation states the unit, \
                 not the span its tract currently occupies, so the bases cannot be spelled \
                 in the description."
            .to_string(),
    };
    ConversionError::MissingReferenceData {
        description: format!(
            "cannot convert to SPDI: the {} bases at {}..={} are unknown (no reference data). \
             {remedy}",
            what.adjective(),
            start_one_based,
            end_one_based,
        ),
    }
}

/// Why the span [`resolve_repeat_tract_span`] returned is the span it returned.
///
/// Exists so a decline can name the caller's own coordinates (#1492). When the
/// search finds no run, the function falls back to the unit-wide span *at* the
/// anchor — which is not something the caller wrote. Reporting that span in an
/// error told the reader to go look at a window they never named: `g.260CAG[5]`
/// declined with "repeat span 260-262 does not match repeat unit CAG", where
/// `260-262` is this function's invention and the caller's actual mistake — that
/// the run begins at 259, not 260 — went unmentioned. 336 of the 560 rows in
/// #1452's census took that path, so it is the common decline, not a corner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RepeatSpanOrigin {
    /// A run was found; the span is its full extent. A unit-match failure here
    /// is a real mismatch over coordinates the search itself chose.
    Tract,
    /// The search ran and found no run at the anchor, so the span is the
    /// unit-wide fallback. This is the case that must not quote its span.
    NoRunAtAnchor,
    /// The search never ran on an input the function does not itself refuse —
    /// an empty unit, an empty sequence, or an anchor past the sequence end. The
    /// span is a placeholder rather than a judgement, so the generic diagnostic
    /// remains the honest one: nothing was measured that would justify saying
    /// "no run begins here". A provider that cannot report a length is *not*
    /// here — that case declines outright (#1497), because the unit-wide span it
    /// would otherwise hand back passes the caller's checks by construction and
    /// converts to a silently truncated triple.
    NotSearched,
}

/// The physical repeat run a single-position repeat anchor names, as a 1-based
/// inclusive span (#1431).
///
/// A start-only repeat (`g.263A[7]`, `g.123CAG[23]`) addresses the whole tandem
/// run it points into, not the one base or one unit at the anchor — see the
/// call site for the spec text and the two ways the one-base reading went
/// wrong. This finds that run with the same routine the normalizer uses
/// ([`crate::normalize::rules::count_tandem_repeats`]) so the two cannot drift
/// apart.
///
/// **Window growth, and why the cap is not a silent truncation.** The tract's
/// extent is not known before it is read, so the reference is fetched in a
/// window around the anchor and the window is doubled while the run still
/// reaches either edge. A tract that is still growing at
/// [`MAX_REPEAT_SEARCH_BASES`] is *declined* rather than reported at the
/// window's width: returning the clamped span would silently under-count the
/// run and emit a triple denoting the wrong bases, which is the exact defect
/// this function exists to remove.
///
/// Falls back to the unit-wide span at the anchor when no run is found — the
/// unit does not match the reference there — so the caller's existing
/// "does not match repeat unit" diagnostic is what reports it, rather than a
/// second error for one condition.
///
/// **The window is normalised before it is searched** (#1452). `unit` arrives
/// having already been through [`apply_alphabet`], so searching the raw window
/// would compare a soft-masked (lowercase) reference against an uppercase unit
/// and find no run at all. That did not surface as an error: the no-run
/// fallback above returns the *unit-wide* span, whose bases the caller then
/// uppercases, so the unit-match check passed and a truncated triple was
/// emitted. On a 3-copy lowercase `cag` tract, `g.259CAG[5]` came out as
/// `258:CAG:CAGCAGCAGCAGCAG` — seven copies once the two untouched tract
/// units are counted — while the range spelling `g.259_267CAG[5]` correctly
/// gave `258:CAGCAGCAG:CAGCAGCAGCAGCAG`. Both spellings converted; they just
/// denoted different sequences.
///
/// Normalising with [`apply_alphabet`] rather than a bare `to_ascii_uppercase`
/// is what keeps the two comparisons provably identical: on the `r.` axis the
/// unit has had `U` rewritten to `T`, so an uppercase-only window would still
/// miss a `U`-spelled tract and truncate it by the same route.
fn resolve_repeat_tract_span<P>(
    provider: &P,
    accession: &str,
    anchor_one_based: u64,
    unit: &[u8],
    alphabet: AlphabetMode,
) -> Result<(u64, u64, RepeatSpanOrigin), ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    /// Half-width of the first window. Comfortably covers the tract lengths the
    /// spec illustrates (its `CAG[23]` example is 69 bases) so the common case
    /// costs one fetch.
    const INITIAL_HALF_WIDTH: u64 = 128;

    if unit.is_empty() {
        return Ok((
            anchor_one_based,
            anchor_one_based,
            RepeatSpanOrigin::NotSearched,
        ));
    }
    let unit_len = unit.len() as u64;
    let fallback = (
        anchor_one_based,
        anchor_one_based.saturating_add(unit_len - 1),
    );

    // A single-position anchor names "the tandem run beginning here", so the
    // run's extent must be *measured* before it can be converted. Measuring it
    // needs the sequence length — to clamp the search window and judge its edges
    // — so a provider that serves bases perfectly well but cannot report a
    // length (`get_sequence_length` carries a trait default that always errors,
    // and no in-repo test can see this because all of ferro's own providers
    // override it) leaves the run unmeasurable.
    //
    // Decline rather than fall back to the unit-wide span at the anchor. That
    // fallback used to be returned here as "a known and stated limit, not a
    // silent wrong span — the caller's divisibility and unit-match checks still
    // judge it", but those checks cannot judge it: a unit-wide span is exactly
    // one unit and passes both *by construction* (divisible, and one unit
    // matched against itself), so the caller converts `g.263A[7]` to a triple
    // denoting a single `A` even where the reference holds a longer run — the
    // same silent truncation as #1452, defeated here by a provider that cannot
    // report a length rather than by soft-masking (#1497). The explicit-range
    // spelling (`g.<start>_<end>{unit}[n]`) carries its own span and never
    // reaches this function, so it is unaffected.
    let Ok(sequence_length) = provider.get_sequence_length(accession) else {
        return Err(ConversionError::UnsupportedEditType {
            description: format!(
                "cannot resolve the repeat tract at {accession}:{anchor_one_based}: the \
                 reference provider could not report the length of {accession}, so the run's \
                 extent could not be verified; spell the whole range explicitly \
                 (`g.<start>_<end>{}[n]`) rather than the start alone",
                String::from_utf8_lossy(unit)
            ),
        });
    };
    if sequence_length == 0 || anchor_one_based > sequence_length {
        return Ok((fallback.0, fallback.1, RepeatSpanOrigin::NotSearched));
    }
    // Now that the length is known, keep the fallback inside the contig: a
    // multi-base unit anchored within `unit_len` of the 3' end would otherwise
    // hand `fetch_reference_bases` a range past the end, replacing the
    // documented "does not match repeat unit" diagnostic with a fetch failure.
    let fallback = (fallback.0, fallback.1.min(sequence_length));

    let mut half_width = INITIAL_HALF_WIDTH;
    loop {
        let window_start = anchor_one_based.saturating_sub(half_width).max(1);
        let window_end = anchor_one_based
            .saturating_add(half_width)
            .min(sequence_length);
        let window = fetch_normalized_reference_bases(
            provider,
            accession,
            window_start,
            window_end,
            alphabet,
        )?;
        let bytes = window.as_bytes();
        let anchor_offset = (anchor_one_based - window_start) as usize;

        let Some((_, tract_start, tract_end)) =
            crate::normalize::rules::count_tandem_repeats(bytes, anchor_offset, unit)
        else {
            return Ok((fallback.0, fallback.1, RepeatSpanOrigin::NoRunAtAnchor));
        };

        // Only grow while the run is still touching an edge the contig has not
        // itself ended at — otherwise the window is not what is bounding it.
        //
        // Both tests are stated in units, not bytes, because
        // `count_tandem_repeats` steps by `unit_len`: a run clipped by the
        // window stops up to `unit_len - 1` bytes short of the edge rather than
        // on it. Testing `tract_end == bytes.len()` therefore only fires when
        // the remaining byte count happens to be a multiple of the unit — true
        // for a 1- or 3-base unit at the initial half-width, false for a 4- or
        // 5-base one — and the clipped span was returned as if it were the whole
        // run. Same on the 5' side: the backward scan stops at
        // `anchor_offset % unit_len`, which need not be 0.
        let open_at_start = tract_start < unit.len() && window_start > 1;
        let open_at_end = tract_end + unit.len() > bytes.len() && window_end < sequence_length;
        if !open_at_start && !open_at_end {
            return Ok((
                window_start + tract_start as u64,
                window_start + tract_end as u64 - 1,
                RepeatSpanOrigin::Tract,
            ));
        }
        // Judged on the whole window, not the half-width, so the figure the
        // message quotes is the window that was actually read.
        if half_width.saturating_mul(2).saturating_add(1) >= MAX_REPEAT_SEARCH_BASES {
            return Err(ConversionError::UnsupportedEditType {
                description: format!(
                    "repeat tract at {accession}:{anchor_one_based} still extends past a \
                     {MAX_REPEAT_SEARCH_BASES}-base search window; spell the whole range \
                     explicitly (`g.<start>_<end>{}[n]`) rather than the start alone",
                    String::from_utf8_lossy(unit)
                ),
            });
        }
        half_width = half_width.saturating_mul(2);
    }
}

/// [`fetch_reference_bases`] with [`apply_alphabet`] already applied, so the
/// caller never holds a window in the reference's own case convention (#1452).
///
/// Reference FASTAs are routinely soft-masked, and the repeat arm compares the
/// fetched bases against a unit that has been through `apply_alphabet` — twice,
/// at two sites. Normalising at the fetch is what stops those two sites from
/// disagreeing: the tract search and the unit-match check now see the same
/// bytes by construction rather than by each remembering to fold. This mirrors
/// how `normalize::merge::canonical_base_byte` centralises the `r.` uracil /
/// thymine equivalence instead of spreading it over its comparison sites.
///
/// The byte offsets a caller computes against the returned string stay valid:
/// `apply_alphabet` rewrites ASCII bytes one-for-one and leaves everything else
/// alone, so the length is preserved. `normalizing_a_window_preserves_its_length`
/// pins that, since a length change would silently mis-map the anchor offset in
/// [`resolve_repeat_tract_span`] rather than fail.
///
/// **Only the repeat arm uses this, and the other arms are not an oversight.**
/// The Duplication / Deletion / Delins / Identity / Inversion arms each fetch
/// through the plain [`fetch_reference_bases`] and fold *after* the `match`,
/// because the bases they fold may instead have come from the description
/// itself (`Some(seq) => sequence_to_string(seq)`, which is a bare
/// `to_string()` and does not fold). Their trailing `apply_alphabet` covers
/// **both** branches. Swapping those fetches to this function would therefore
/// not let the trailing fold be removed — it would only normalize the fetched
/// branch twice, and removing the fold along with it would silently stop
/// normalizing author-spelled bases. This arm is different precisely because it
/// has no author-spelled branch: an unspelled repeat tract is the only way in,
/// so the fetch is the single source and folding there is what makes the tract
/// search and the unit-match check agree by construction.
fn fetch_normalized_reference_bases<P>(
    provider: &P,
    accession: &str,
    start_one_based: u64,
    end_one_based: u64,
    alphabet: AlphabetMode,
) -> Result<String, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    let raw = fetch_reference_bases(provider, accession, start_one_based, end_one_based)?;
    let normalized = apply_alphabet(&raw, alphabet);
    debug_assert_eq!(
        normalized.len(),
        raw.len(),
        "alphabet normalization must preserve byte length"
    );
    Ok(normalized)
}

/// Fetch reference bases for a 1-based inclusive interval `[start, end]` on
/// `accession`. Tries [`ReferenceProvider::get_genomic_sequence`] first
/// (correct for `g.`/`m.` and natural for genomic accessions) and falls
/// back to [`ReferenceProvider::get_sequence`] for transcript accessions
/// (`n.`/`r.`/`c.` SPDI emits on the transcript accession per #116).
///
/// The provider takes 0-based half-open coordinates, so the conversion is
/// `[start - 1, end)`.
///
/// Returns [`ConversionError::MissingReferenceData`] when neither call
/// returns data, or when the returned string length does not match the
/// requested interval length (insufficient ref data near a boundary).
fn fetch_reference_bases<P>(
    provider: &P,
    accession: &str,
    start_one_based: u64,
    end_one_based: u64,
) -> Result<String, ConversionError>
where
    P: ReferenceProvider + ?Sized,
{
    if start_one_based < 1 || end_one_based < start_one_based {
        return Err(ConversionError::InvalidPosition {
            description: format!(
                "invalid 1-based interval [{}, {}] for reference fetch",
                start_one_based, end_one_based
            ),
        });
    }
    let zb_start = start_one_based - 1;
    let zb_end = end_one_based;
    let expected_len = (zb_end - zb_start) as usize;

    let bases = match provider.get_genomic_sequence(accession, zb_start, zb_end) {
        Ok(s) => s,
        Err(_) => provider
            .get_sequence(accession, zb_start, zb_end)
            .map_err(|e| ConversionError::MissingReferenceData {
                description: format!(
                    "could not fetch reference for {}:{}-{}: {}",
                    accession, start_one_based, end_one_based, e
                ),
            })?,
    };

    if bases.len() != expected_len {
        return Err(ConversionError::MissingReferenceData {
            description: format!(
                "reference fetch for {}:{}-{} returned {} bases, expected {}",
                accession,
                start_one_based,
                end_one_based,
                bases.len(),
                expected_len
            ),
        });
    }
    Ok(bases)
}

/// Rewrite RNA-alphabet characters to the DNA alphabet for SPDI output.
///
/// SPDI uses the DNA alphabet by convention (RefSeq stores transcript
/// sequences as DNA even on `NR_*` and `NM_*` accessions), so RNA `u`/`U`
/// must become `T`. Other characters are returned unchanged. The output is
/// always uppercase to match SPDI's standard form.
pub(crate) fn apply_alphabet(s: &str, alphabet: AlphabetMode) -> String {
    match alphabet {
        AlphabetMode::Dna => s.to_ascii_uppercase(),
        AlphabetMode::Rna => s
            .chars()
            .map(|c| match c.to_ascii_uppercase() {
                'U' => 'T',
                other => other,
            })
            .collect(),
    }
}

/// Convert an SPDI variant to HGVS genomic format.
///
/// # Arguments
///
/// * `spdi` - The SPDI variant to convert
///
/// # Returns
///
/// * `Ok(HgvsVariant)` - Successfully converted variant
/// * `Err(ConversionError)` - Conversion failed
///
/// # Examples
///
/// ```
/// use ferro_hgvs::spdi::{SpdiVariant, convert::spdi_to_hgvs};
///
/// let spdi = SpdiVariant::new("NC_000001.11", 12344, "A", "G");
/// let hgvs = spdi_to_hgvs(&spdi).unwrap();
/// assert_eq!(hgvs.to_string(), "NC_000001.11:g.12345A>G");
/// ```
pub fn spdi_to_hgvs(spdi: &SpdiVariant) -> Result<HgvsVariant, ConversionError> {
    // Parse the accession using the HGVS parser
    let accession = parse_accession(&spdi.sequence)
        .map(|(_, acc)| acc)
        .map_err(|_| ConversionError::InvalidAccession {
            description: format!("could not parse accession: {}", spdi.sequence),
        })?;

    // Convert 0-based SPDI position to 1-based HGVS position using type-safe conversion
    let spdi_pos_zb = ZeroBasedPos::new(spdi.position);
    let hgvs_pos_ob = spdi_pos_zb.to_one_based();
    let hgvs_pos = hgvs_pos_ob.value();

    // Determine the edit type based on deletion and insertion
    let (interval, edit) = if spdi.is_identity() {
        // A zero-width triple (`NC_000001.11:99::`) names no bases at all, so
        // there is no interval it could be an identity over. Emitting one
        // anyway rendered `g.100=`, an identity asserting a base the triple
        // never claimed — the reverse-direction twin of the invent-a-base
        // error #1362 fixed on the way out. `is_identity()` is `deletion ==
        // insertion`, so a both-empty triple reaches this arm and not the
        // deletion/insertion ones below; refusing here covers it.
        if spdi.deletion.is_empty() {
            return Err(ConversionError::UnsupportedEditType {
                description: "a zero-width SPDI triple names no bases, so it cannot be \
                              converted to an identity over an interval"
                    .to_string(),
            });
        }
        let seq = Some(string_to_sequence(&spdi.deletion)?);
        // An identity claims every base in its triple, so a multi-base one
        // needs a span interval — a point interval would render `g.27GT=`,
        // whose location says one base while its sequence says two. Mirrors
        // the `is_deletion()` arm below.
        let del_len = spdi.deletion.len();
        let interval = if del_len > 1 {
            Interval::new(
                GenomePos::new(hgvs_pos),
                GenomePos::new(hgvs_pos + del_len as u64 - 1),
            )
        } else {
            Interval::point(GenomePos::new(hgvs_pos))
        };
        (
            interval,
            NaEdit::Identity {
                sequence: seq,
                whole_entity: false,
            },
        )
    } else if spdi.deletion.len() == 1 && spdi.insertion.len() == 1 {
        // SNV substitution
        let ref_base = char_to_base(spdi.deletion.chars().next().unwrap())?;
        let alt_base = char_to_base(spdi.insertion.chars().next().unwrap())?;
        (
            Interval::point(GenomePos::new(hgvs_pos)),
            NaEdit::Substitution {
                reference: ref_base,
                alternative: alt_base,
            },
        )
    } else if spdi.is_deletion() {
        // Pure deletion
        let del_len = spdi.deletion.len();
        let del_seq = string_to_sequence(&spdi.deletion)?;
        let interval = if del_len > 1 {
            Interval::new(
                GenomePos::new(hgvs_pos),
                GenomePos::new(hgvs_pos + del_len as u64 - 1),
            )
        } else {
            Interval::point(GenomePos::new(hgvs_pos))
        };
        (
            interval,
            NaEdit::Deletion {
                sequence: Some(del_seq),
                length: None,
            },
        )
    } else if spdi.is_insertion() {
        // Pure insertion. SPDI position N is the 0-based interbase
        // boundary AFTER 1-based base N — i.e. an insertion at SPDI
        // position N corresponds to HGVS `g.N_(N+1)ins{seq}`. Pre-#390
        // this incorrectly used `hgvs_pos = spdi.position + 1`, shifting
        // every emitted ins-form interval by one (`g.(N+1)_(N+2)ins…`).
        // SPDI position 0 represents an insertion before the first
        // base; HGVS has no notation for it, so reject up-front rather
        // than silently emit `g.0_1ins…`.
        if spdi.position == 0 {
            return Err(ConversionError::InvalidPosition {
                description: "SPDI position 0 represents an insertion before the \
                    first base, which has no HGVS notation"
                    .to_string(),
            });
        }
        let ins_seq = string_to_sequence(&spdi.insertion)?;
        (
            Interval::new(
                GenomePos::new(spdi.position),
                GenomePos::new(spdi.position + 1),
            ),
            NaEdit::Insertion {
                sequence: InsertedSequence::Literal(ins_seq),
            },
        )
    } else if !spdi.deletion.is_empty()
        && spdi.deletion.len() == spdi.insertion.len()
        && spdi.deletion.len() >= 2
        && reverse_complement(&spdi.deletion).eq_ignore_ascii_case(&spdi.insertion)
    {
        // Inversion recovery (#270): SPDI delins where the inserted seq
        // is the reverse complement of the deleted seq is canonically a
        // tandem inversion. Length-1 cases are SNVs and handled above;
        // self-RC palindromes of length 2+ (e.g. `AT:AT`, `GC:GC`) only
        // recover when the seqs differ from a plain identity — which
        // they don't, so identity catches them first.
        let inv_seq = string_to_sequence(&spdi.deletion)?;
        let del_len = spdi.deletion.len();
        let interval = Interval::new(
            GenomePos::new(hgvs_pos),
            GenomePos::new(hgvs_pos + del_len as u64 - 1),
        );
        (
            interval,
            NaEdit::Inversion {
                sequence: Some(inv_seq),
                length: None,
            },
        )
    } else {
        // Delins (different lengths or MNV)
        let del_len = spdi.deletion.len();
        let ins_seq = string_to_sequence(&spdi.insertion)?;
        let interval = if del_len > 1 {
            Interval::new(
                GenomePos::new(hgvs_pos),
                GenomePos::new(hgvs_pos + del_len as u64 - 1),
            )
        } else {
            Interval::point(GenomePos::new(hgvs_pos))
        };
        (
            interval,
            NaEdit::Delins {
                sequence: InsertedSequence::Literal(ins_seq),
                deleted: None,
                deleted_length: None,
                substitution_reference: None,
            },
        )
    };

    // m. coord system recovery (#270): NC_012920.* is the canonical
    // human mitochondrial accession; SPDI carries no coord-system tag
    // so the bare reverse path defaults to g. Emit m. when the
    // accession matches a known mitochondrial reference.
    if is_mitochondrial_accession(&accession) {
        return Ok(HgvsVariant::Mt(MtVariant {
            accession,
            gene_symbol: None,
            loc_edit: LocEdit::new(interval, edit),
        }));
    }

    Ok(HgvsVariant::Genome(GenomeVariant {
        accession,
        gene_symbol: None,
        loc_edit: LocEdit::new(interval, edit),
    }))
}

/// Returns true if `accession` is a known mitochondrial reference. Used
/// by `spdi_to_hgvs` to emit `m.` instead of `g.` for these accessions
/// (SPDI carries no coord-system tag). Delegates to
/// [`Accession::is_mitochondrial`], the single source for the accession list.
fn is_mitochondrial_accession(accession: &Accession) -> bool {
    accession.is_mitochondrial()
}

/// Convert an SPDI variant to HGVS, using a reference provider to recover
/// duplication form for SPDI insertions whose inserted sequence equals the
/// immediately-5' reference flank.
///
/// SPDI is a canonical/positional format and represents duplications as
/// insertions of the duplicated sequence. This function performs the inverse
/// recovery for HGVS round-trips: given an SPDI insertion, if the
/// `inserted.len()` reference bases ending at the insertion point equal the
/// inserted sequence (case-insensitive), the change is a tandem duplication
/// per the HGVS spec
/// (`assets/hgvs-nomenclature/docs/recommendations/DNA/duplication.md`) and
/// is rendered as HGVS `dup` rather than `ins`.
///
/// All other SPDI shapes (substitution, deletion, delins, identity) are
/// returned unchanged from [`spdi_to_hgvs`].
///
/// SPDI itself is canonical and places the insertion at its rightmost
/// shiftable offset, so the matched 5' flank is already the most-3' position;
/// no separate 3' shift is performed.
///
/// SPDI→HGVS only produces genomic (`g.`) variants, so dup recovery applies
/// uniformly to genomic and mitochondrial accessions but does not extend to
/// `c.`, `n.`, or `r.` coordinate systems via this function.
///
/// # Arguments
///
/// * `spdi` - The SPDI variant to convert.
/// * `reference` - Reference provider used to fetch the 5'-flanking bases
///   for dup detection. The function tries
///   [`ReferenceProvider::get_genomic_sequence`] first and falls back to
///   [`ReferenceProvider::get_sequence`] for providers that only expose
///   sequences via the transcript path.
///
/// # Errors
///
/// Returns [`ConversionError::MissingReferenceData`] when the reference
/// provider returns an error fetching the 5' flank. Returns the same errors
/// as [`spdi_to_hgvs`] for other failure modes. A short fetch (truncated near
/// a contig boundary) or a non-matching flank silently falls back to the
/// ins-form result, matching the spec recommendation that, absent evidence
/// of tandem flanking, the change is described as an insertion.
///
/// [`ReferenceProvider`]: crate::reference::provider::ReferenceProvider
/// [`ReferenceProvider::get_genomic_sequence`]: crate::reference::provider::ReferenceProvider::get_genomic_sequence
/// [`ReferenceProvider::get_sequence`]: crate::reference::provider::ReferenceProvider::get_sequence
pub fn spdi_to_hgvs_with_ref<R>(
    spdi: &SpdiVariant,
    reference: &R,
) -> Result<HgvsVariant, ConversionError>
where
    R: crate::reference::provider::ReferenceProvider + ?Sized,
{
    // Build the base HGVS variant using the existing reference-free path.
    let base = spdi_to_hgvs(spdi)?;

    // Only insertions are candidates for dup recovery. Everything else
    // (substitution, deletion, delins, identity) passes through unchanged.
    if !spdi.is_insertion() {
        return Ok(base);
    }

    // Try to recover dup form. If the inserted sequence does not match the
    // 5' flank, fall through and return the original `ins`-form variant.
    if let Some(dup_variant) = recover_dup_from_insertion(spdi, reference, &base)? {
        return Ok(dup_variant);
    }
    Ok(base)
}

/// If the SPDI insertion's inserted sequence equals the immediately-5'
/// reference flank (case-insensitive), return an `HgvsVariant` whose edit is
/// `NaEdit::Duplication` over the corresponding 1-based interval. Returns
/// `Ok(None)` when the bases do not match or there are not enough preceding
/// bases. Returns `Err` only when the reference provider returns a hard
/// fetch error (which is propagated as `MissingReferenceData`).
///
/// `base` is the already-built `ins`-form `HgvsVariant`; we reuse its
/// accession and gene_symbol when constructing the dup-form result.
fn recover_dup_from_insertion<R>(
    spdi: &SpdiVariant,
    reference: &R,
    base: &HgvsVariant,
) -> Result<Option<HgvsVariant>, ConversionError>
where
    R: crate::reference::provider::ReferenceProvider + ?Sized,
{
    debug_assert!(spdi.is_insertion());

    let ins = &spdi.insertion;
    let ins_len = ins.len() as u64;
    if ins_len == 0 {
        return Ok(None);
    }

    // Need `ins_len` bases of preceding reference. SPDI position N is
    // the 0-based interbase boundary AFTER 1-based base N, so the
    // 5'-flanking window is the `ins_len` bases ending at HGVS 1-based
    // position `spdi.position`. In the 0-based half-open form used by
    // `get_genomic_sequence` that's `[spdi.position - ins_len, spdi.position)`.
    let flank_end = spdi.position;
    if flank_end < ins_len {
        // Not enough preceding bases (insertion is too close to contig 5' end).
        return Ok(None);
    }
    let flank_start = flank_end - ins_len;

    // Fetch the flanking sequence. Try `get_genomic_sequence` first (the
    // SPDI accession is genomic), then fall back to `get_sequence` for
    // providers that store contigs as transcripts.
    let flank = match reference.get_genomic_sequence(&spdi.sequence, flank_start, flank_end) {
        Ok(s) => s,
        Err(_) => match reference.get_sequence(&spdi.sequence, flank_start, flank_end) {
            Ok(s) => s,
            Err(e) => {
                return Err(ConversionError::MissingReferenceData {
                    description: format!(
                        "could not fetch 5' flank for {}:{}-{}: {}",
                        spdi.sequence, flank_start, flank_end, e
                    ),
                });
            }
        },
    };

    // The fetched window must match `ins` (case-insensitive) and must be
    // exactly `ins_len` bases. A short fetch (e.g., truncated near a contig
    // boundary) means we cannot prove tandem dup → fall back to ins.
    if flank.len() as u64 != ins_len {
        return Ok(None);
    }
    if !flank.eq_ignore_ascii_case(ins) {
        return Ok(None);
    }

    // Build the dup edit. The SPDI 0-based interbase position N and
    // the HGVS 1-based base-N coordinate share the same numeric
    // value (N), even though they describe different things —
    // `spdi.position` (interbase) sits AFTER 1-based base
    // `spdi.position`, which is also the 1-based end of the
    // duplicated region.
    let end_one_based = flank_end; // numerically equal to spdi.position
    let start_one_based = end_one_based + 1 - ins_len;

    let dup_seq = string_to_sequence(ins)?;
    let interval = if ins_len == 1 {
        Interval::point(GenomePos::new(end_one_based))
    } else {
        Interval::new(
            GenomePos::new(start_one_based),
            GenomePos::new(end_one_based),
        )
    };
    let edit = NaEdit::Duplication {
        sequence: Some(dup_seq),
        length: None,
        uncertain_extent: None,
    };

    // Reuse the accession + gene_symbol from the base ins-form variant.
    // SPDI→HGVS produces either Genome or Mt (mitochondrial), depending
    // on the accession; preserve whichever shape the base has.
    match base {
        HgvsVariant::Genome(g) => Ok(Some(HgvsVariant::Genome(GenomeVariant {
            accession: g.accession.clone(),
            gene_symbol: g.gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }))),
        HgvsVariant::Mt(m) => Ok(Some(HgvsVariant::Mt(MtVariant {
            accession: m.accession.clone(),
            gene_symbol: m.gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }))),
        _ => Ok(None),
    }
}

/// Helper to convert a string to a Sequence.
fn string_to_sequence(s: &str) -> Result<Sequence, ConversionError> {
    s.parse().map_err(|_| ConversionError::InvalidPosition {
        description: format!("invalid sequence: {}", s),
    })
}

/// Helper to convert a char to a Base.
fn char_to_base(c: char) -> Result<crate::hgvs::edit::Base, ConversionError> {
    crate::hgvs::edit::Base::from_char(c).ok_or_else(|| ConversionError::InvalidPosition {
        description: format!("invalid base character: {}", c),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hgvs::parser::parse_hgvs;

    /// Build an `n.*N` substitution.
    ///
    /// #1748 refuses that spelling at parse in **every** mode
    /// (`background/numbering.md:52` puts no `*` zone on the non-coding axis),
    /// so a downstream fixture can no longer be parsed. It still has to be
    /// *handled* here: [`TxPos::downstream`](crate::hgvs::location::TxPos::downstream)
    /// is public API, so a caller can hand the conversion path one of these
    /// without the parser ever seeing it. Constructing it is therefore the
    /// faithful fixture, not a workaround.
    fn tx_downstream_sub(accession: &str, base: i64) -> crate::hgvs::HgvsVariant {
        use crate::hgvs::interval::TxInterval;
        use crate::hgvs::location::TxPos;
        let mut variant =
            parse_hgvs(&format!("{accession}:n.{base}A>G")).expect("the template parses");
        let crate::hgvs::HgvsVariant::Tx(tx) = &mut variant else {
            unreachable!("an `n.` description parses as Tx")
        };
        tx.loc_edit.location = TxInterval::point(TxPos::downstream(base));
        variant
    }

    // ------------------------------------------------------------------
    // Unspelled-bases declines (#1388)
    //
    // These pin the message *text*, not just that an error occurs. The arms
    // were already covered for behaviour, which is exactly why a wrapping
    // defect could sit in a branch through a full green suite: nothing read
    // what they said.
    // ------------------------------------------------------------------

    /// Every example offered in a decline must be a description ferro accepts.
    /// Suggesting a form the parser rejects would send the caller somewhere
    /// worse than saying nothing, and the suggestion is a literal that no other
    /// test exercises.
    #[test]
    fn spelled_examples_are_parseable() {
        for what in [
            UnspelledBases::Duplicated,
            UnspelledBases::Deleted,
            UnspelledBases::DeletedInDelins,
            UnspelledBases::Unchanged,
            UnspelledBases::Inverted,
            UnspelledBases::RepeatTract,
        ] {
            let Some(example) = what.spelled_example() else {
                // `RepeatTract` offers no example on purpose — the notation
                // cannot carry the bases. Assert that rather than skipping it,
                // so adding an example here without a parseable form fails.
                assert_eq!(
                    what,
                    UnspelledBases::RepeatTract,
                    "only the repeat tract may decline without offering an example"
                );
                continue;
            };
            let prefixed = format!("NC_000001.11:{example}");
            assert!(
                parse_hgvs(&prefixed).is_ok(),
                "{what:?} suggests `{example}`, which ferro cannot parse as `{prefixed}`"
            );
        }
    }

    /// The repeat arm names the provider as the only route, and does not tell the
    /// caller to spell bases the notation cannot express.
    #[test]
    fn the_repeat_tract_offers_only_the_provider() {
        let message = unspelled_bases_error(UnspelledBases::RepeatTract, 10, 12).to_string();
        assert!(message.contains("10..=12"), "no span named: {message}");
        assert!(
            message.contains("reference provider"),
            "the provider route must be named: {message}"
        );
        assert!(
            !message.contains("Spell them"),
            "a repeat's tract cannot be spelled in the description, so the message \
             must not suggest it: {message}"
        );
    }

    /// The rendered message must carry no accidental whitespace runs. A wrapped
    /// literal without `\` continuations silently embeds the source indentation,
    /// which is invisible in review and obvious to a user.
    #[test]
    fn the_decline_message_has_no_embedded_whitespace_runs() {
        // Every shape, not a representative one: the defect is per-literal, and
        // each shape's message is assembled from a different pair of literals.
        for what in [
            UnspelledBases::Duplicated,
            UnspelledBases::Deleted,
            UnspelledBases::DeletedInDelins,
            UnspelledBases::Unchanged,
            UnspelledBases::Inverted,
            UnspelledBases::RepeatTract,
        ] {
            let message = unspelled_bases_error(what, 10, 12).to_string();
            assert!(
                !message.contains("  "),
                "{what:?} carries a run of consecutive spaces: {message:?}"
            );
            assert!(
                !message.contains('\n') && !message.contains('\t'),
                "{what:?} carries a newline or tab: {message:?}"
            );
        }
    }

    /// The whole point of the message: it names the interval that could not be
    /// resolved, and both ways out.
    #[test]
    fn the_decline_message_names_the_span_and_both_remedies() {
        let message = unspelled_bases_error(UnspelledBases::Unchanged, 10, 12).to_string();
        assert!(message.contains("10..=12"), "no span named: {message}");
        assert!(message.contains("unchanged"), "no shape named: {message}");
        assert!(message.contains("g.10A="), "no example offered: {message}");
        assert!(
            message.contains("Spell them") && message.contains("reference provider"),
            "both remedies must be offered: {message}"
        );
    }

    /// The six shapes must be distinguishable from their messages alone — a
    /// caller reading a log has nothing else to go on.
    #[test]
    fn each_shape_declines_distinguishably() {
        let messages: Vec<String> = [
            UnspelledBases::Duplicated,
            UnspelledBases::Deleted,
            UnspelledBases::DeletedInDelins,
            UnspelledBases::Unchanged,
            UnspelledBases::Inverted,
            UnspelledBases::RepeatTract,
        ]
        .iter()
        .map(|w| unspelled_bases_error(*w, 10, 12).to_string())
        .collect();

        // `Deleted` and `DeletedInDelins` share an adjective by design — both
        // are the deleted span — but differ in the example they offer.
        let unique: std::collections::BTreeSet<&String> = messages.iter().collect();
        assert_eq!(
            unique.len(),
            messages.len(),
            "two shapes decline identically: {messages:#?}"
        );
    }

    /// End-to-end: the message a real provider-less conversion produces, for
    /// each shape that can hit the wall. Pins that the helper is actually wired
    /// in — a unit test on the helper alone would pass with the arms unchanged.
    ///
    /// All **six** shapes, including the repeat tract. It is the one arm whose
    /// remedy differs, so leaving it to the helper-level tests would have left
    /// the only differing branch unproven end-to-end — and it is reachable
    /// without a provider exactly like its siblings.
    #[test]
    fn a_provider_less_conversion_declines_with_the_span() {
        for (descriptor, adjective, span) in [
            ("NC_000001.11:g.10_12dup", "duplicated", "10..=12"),
            ("NC_000001.11:g.10_12del", "deleted", "10..=12"),
            ("NC_000001.11:g.10_12delinsT", "deleted", "10..=12"),
            ("NC_000001.11:g.10_12=", "unchanged", "10..=12"),
            ("NC_000001.11:g.10_12inv", "inverted", "10..=12"),
            (
                "NC_000001.11:g.10_15AC[3]",
                "pre-expansion repeat-tract",
                "10..=15",
            ),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            let message = hgvs_to_spdi_simple(&variant)
                .expect_err(&format!("`{descriptor}` must decline without a provider"))
                .to_string();
            assert!(
                message.contains(adjective) && message.contains(span),
                "`{descriptor}` declined without naming the {adjective} bases at {span}: {message}"
            );
        }
    }

    // HGVS to SPDI tests

    #[test]
    fn test_hgvs_to_spdi_substitution() {
        let hgvs = parse_hgvs("NC_000001.11:g.12345A>G").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.sequence, "NC_000001.11");
        assert_eq!(spdi.position, 12344);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_insertion() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI 0-based interbase: position 100 is the boundary AFTER
        // 1-based base 100, matching HGVS g.100_101ins (closes #390).
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_deletion_with_seq() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn test_hgvs_to_spdi_deletion_without_seq() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    #[test]
    fn test_hgvs_to_spdi_delins_without_ref() {
        // Without reference data, delins with unknown deletion sequence returns error
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delinsTTCC").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unknown"));
    }

    #[test]
    fn test_hgvs_to_spdi_delins_with_explicit_deleted_no_ref() {
        // Issue #120: when the input carries an explicit deleted sequence, the
        // SPDI conversion can succeed without reference data.
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delATGinsTTCC").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs)
            .expect("explicit deleted sequence should not require reference data");
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "TTCC");
    }

    #[test]
    fn test_hgvs_to_spdi_duplication_with_seq() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_102dupATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // Dup becomes insertion after the duplicated region; SPDI
        // interbase position 102 sits AFTER 1-based base 102 (#390).
        assert_eq!(spdi.position, 102);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_identity() {
        let hgvs = parse_hgvs("NC_000001.11:g.100A=").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "A");
    }

    // ------------------------------------------------------------------
    // Reference-window normalization (#1452)
    //
    // The soft-masking behaviour these underwrite is graded end-to-end in
    // `tests/it/issue_1452_soft_masked_repeat_span.rs`. What lives here are
    // the two properties that cannot be isolated from there: the length
    // invariant the anchor offset depends on, and the `r.` axis, which the
    // integration suite reaches only through a full transcript projection.
    // ------------------------------------------------------------------

    /// `resolve_repeat_tract_span` computes `anchor_offset` as a byte index
    /// into the normalized window, so a normalization that changed the byte
    /// length would silently point the tract search at the wrong base rather
    /// than fail. Both `apply_alphabet` arms rewrite ASCII one-for-one and
    /// leave every other byte alone, and this is what holds them to it.
    #[test]
    fn normalizing_a_window_preserves_its_length() {
        for window in ["acgtACGT", "uuuUUU", "acgunACGUN", "", "nnnn"] {
            for alphabet in [AlphabetMode::Dna, AlphabetMode::Rna] {
                assert_eq!(
                    apply_alphabet(window, alphabet).len(),
                    window.len(),
                    "`{window}` changed length under {alphabet:?}"
                );
            }
        }
    }

    /// The window is normalized with `apply_alphabet`, not `to_ascii_uppercase`,
    /// and on the `r.` axis that is the difference between finding a tract and
    /// truncating it.
    ///
    /// A repeat unit reaches `resolve_repeat_tract_span` having already had `U`
    /// rewritten to `T` for SPDI's DNA alphabet, so a `u`-spelled reference must
    /// get the same rewrite or the search compares `T` against `U` and finds no
    /// run — the identical silent-truncation route #1452 fixed for case. The
    /// `Dna` row is the control: there `U` is not `T`, so no tract exists and
    /// the unit-wide fallback is the right answer.
    #[test]
    fn a_uracil_spelled_tract_is_found_on_the_rna_axis() {
        let mut provider = MockProvider::new();
        // A 4-copy `u` tract at 3..=6, lower-case as well, so this covers both
        // normalizations at once.
        provider.add_genomic_sequence("NR_TEST.1", "GGuuuuGG".to_string());

        assert_eq!(
            resolve_repeat_tract_span(&provider, "NR_TEST.1", 3, b"T", AlphabetMode::Rna).unwrap(),
            (3, 6, RepeatSpanOrigin::Tract),
            "the `r.` axis must see the tract its unit was rewritten to match"
        );
        assert_eq!(
            resolve_repeat_tract_span(&provider, "NR_TEST.1", 3, b"T", AlphabetMode::Dna).unwrap(),
            (3, 3, RepeatSpanOrigin::NoRunAtAnchor),
            "on the DNA axis `U` is not `T`, so no tract exists and the \
             unit-wide fallback stands"
        );
    }

    /// A provider that serves bases perfectly but refuses every length lookup,
    /// modelling the out-of-tree `ReferenceProvider` #1497 is about: one whose
    /// `get_sequence`/`get_genomic_sequence` work while `get_sequence_length`
    /// cannot answer — a lazily-indexed store, or one leaning on the trait's
    /// always-erroring default. All of ferro's own providers override
    /// `get_sequence_length`, so this state is unreachable without a purpose-
    /// built stand-in.
    struct LengthlessProvider(MockProvider);

    impl ReferenceProvider for LengthlessProvider {
        fn get_transcript(&self, id: &str) -> Result<std::sync::Arc<Transcript>, FerroError> {
            self.0.get_transcript(id)
        }

        fn get_sequence(&self, id: &str, start: u64, end: u64) -> Result<String, FerroError> {
            self.0.get_sequence(id, start, end)
        }

        fn get_genomic_sequence(
            &self,
            contig: &str,
            start: u64,
            end: u64,
        ) -> Result<String, FerroError> {
            self.0.get_genomic_sequence(contig, start, end)
        }

        /// The single deviation from the wrapped provider: no length, ever.
        fn get_sequence_length(&self, id: &str) -> Result<u64, FerroError> {
            Err(FerroError::ReferenceNotFound { id: id.to_string() })
        }
    }

    /// A 13-base contig `GGCAGCAGCAGGG` carrying a 3-copy `CAG` tract at
    /// 1-based positions 3..=11, so the anchored spelling `g.3CAG[5]` and the
    /// range spelling `g.3_11CAG[5]` name the same run.
    fn cag_tract_provider() -> MockProvider {
        let mut provider = MockProvider::new();
        provider.add_genomic_sequence("NC_TEST.1", "GGCAGCAGCAGGG".to_string());
        provider
    }

    /// When the tract search cannot run — here because `get_sequence_length`
    /// fails — an anchored repeat must DECLINE rather than convert on the
    /// unverified unit-wide span. The unit-wide fallback trivially satisfies the
    /// caller's divisibility and unit-match checks (it is exactly one unit,
    /// matched against itself), so those checks cannot stand in for the search
    /// and the fallback would emit a triple denoting a single `CAG` where the
    /// reference holds three (#1497). The explicit-range spelling carries its
    /// own span, needs no search, and must still convert.
    #[test]
    fn an_anchored_repeat_declines_when_the_length_lookup_fails() {
        let provider = LengthlessProvider(cag_tract_provider());

        // The anchored spelling relies on searching for the run, which needs the
        // length. With the length unavailable it declines rather than truncating.
        let anchored = parse_hgvs("NC_TEST.1:g.3CAG[5]").unwrap();
        let err = hgvs_to_spdi(&anchored, &provider)
            .expect_err("an anchored repeat must decline when the tract span cannot be verified");
        assert!(
            matches!(err, ConversionError::UnsupportedEditType { .. }),
            "declining an unverifiable anchored tract, got {err:?}"
        );

        // The explicit range names its own span and reads its bases directly, so
        // a failed length lookup does not stop it converting.
        let ranged = parse_hgvs("NC_TEST.1:g.3_11CAG[5]").unwrap();
        let spdi = hgvs_to_spdi(&ranged, &provider)
            .expect("the explicit-range spelling carries its own span and needs no length");
        assert_eq!(spdi.position, 2);
        assert_eq!(spdi.deletion, "CAGCAGCAG");
        assert_eq!(spdi.insertion, "CAGCAGCAGCAGCAG");
    }

    /// The control: with a healthy provider the same anchored spelling searches
    /// out the full 3-copy run and converts over its whole extent — identically
    /// to the range spelling — so the decline above is scoped to the failed
    /// search and does not regress the normal path (#1497).
    #[test]
    fn an_anchored_repeat_converts_over_its_full_run_when_the_length_is_known() {
        let provider = cag_tract_provider();

        let anchored = parse_hgvs("NC_TEST.1:g.3CAG[5]").unwrap();
        let spdi = hgvs_to_spdi(&anchored, &provider)
            .expect("a healthy provider resolves the anchored tract");
        assert_eq!(spdi.position, 2);
        assert_eq!(spdi.deletion, "CAGCAGCAG");
        assert_eq!(spdi.insertion, "CAGCAGCAGCAGCAG");

        let ranged = parse_hgvs("NC_TEST.1:g.3_11CAG[5]").unwrap();
        assert_eq!(hgvs_to_spdi(&ranged, &provider).unwrap(), spdi);
    }

    /// A 28-base `ACGT…` contig, so a 1-based position `p` holds
    /// `"ACGT"[(p - 1) % 4]` — base 10 is `C`, and 10..12 is `CGT`.
    fn identity_provider() -> MockProvider {
        let mut provider = MockProvider::new();
        provider.add_genomic_sequence("NC_000001.11", "ACGTACGTACGTACGTACGTACGTACGT".to_string());
        provider
    }

    #[test]
    fn an_unspelled_identity_takes_its_base_from_the_reference() {
        // `g.10=` states that base 10 is unchanged without naming it. Every
        // other arm that can omit its sequence (deletion, delins, inversion)
        // fetches it from the provider; this one used to default to the empty
        // string, yielding a zero-width `99::` that claims no base at all.
        let hgvs = parse_hgvs("NC_000001.11:g.10=").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "C");
        assert_eq!(spdi.insertion, "C");
    }

    #[test]
    fn an_unspelled_identity_takes_its_whole_span_from_the_reference() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12=").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "CGT");
    }

    /// A same-reference position-range insertion (`ins{start}_{end}`) names its
    /// inserted bases by position rather than spelling them, so `hgvs_to_spdi`
    /// must read them from the reference — exactly as `del`/`dup` read their
    /// omitted bases. On the `ACGT…` contig positions 5..=8 hold `ACGT`.
    #[test]
    fn a_reference_span_insertion_reads_its_bases_from_the_reference() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_11ins5_8").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        // SPDI interbase position 10 sits AFTER 1-based base 10 (#390).
        assert_eq!(spdi.position, 10);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ACGT");
    }

    /// The inverted form (`ins{start}_{end}inv`) inserts the reverse complement
    /// of the named span. Positions 5..=7 hold `ACG`, whose reverse complement
    /// is `CGT` (a non-palindromic span, so the inversion is observable).
    #[test]
    fn an_inverted_reference_span_insertion_reads_the_reverse_complement() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_11ins5_7inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 10);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "CGT");
    }

    /// A range insert names bases in the reference, so without a provider to
    /// read them the conversion must decline rather than invent them.
    #[test]
    fn a_reference_span_insertion_without_a_provider_is_declined() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_11ins5_8").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::MissingReferenceData { .. })),
            "a same-reference range insert cannot be resolved without a provider: {result:?}"
        );
    }

    /// The `delins` arm resolves a same-reference range insert on the same path,
    /// fetching both the deleted span and the inserted span from the reference.
    /// del at 10..=12 is `CGT`; ins 5..=8 is `ACGT`.
    #[test]
    fn a_reference_span_delins_reads_both_spans_from_the_reference() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins5_8").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "ACGT");
    }

    /// An exact tandem-repeat insertion (`ins{unit}[{n}]`) names its inserted
    /// bases by a spelled unit and an exact copy count. `hgvs_to_spdi` expands
    /// the unit `n` times — no provider is needed, since the bases are named in
    /// the description itself — so the simple path resolves it.
    #[test]
    fn an_exact_repeat_insertion_expands_its_unit() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insC[4]").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI interbase position 100 sits AFTER 1-based base 100 (#390).
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "CCCC");
    }

    /// A multi-base unit (`ins{unit}[{n}]` with `unit` longer than one base)
    /// repeats the whole unit `n` times.
    #[test]
    fn an_exact_multibase_repeat_insertion_expands_the_whole_unit() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insCG[3]").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "CGCGCG");
    }

    /// An uncertain or range copy count (`ins{unit}[{min}_{max}]`, `[?]`) names
    /// no single expansion, so it stays undetermined and must decline.
    #[test]
    fn an_uncertain_repeat_count_insertion_is_declined() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insC[10_15]").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::MissingReferenceData { .. })),
            "a range repeat count names no single expansion: {result:?}"
        );
    }

    /// An `N`-unit repeat insertion (`insN[18]`) carries a *length*, not bases —
    /// the same information content as the `ins<length>` shape (`ins341`,
    /// `InsertedSequence::Count`) SPDI already refuses (#1967). Emitting a run of
    /// `N`s would assert 18 specific bases the input never specified, a
    /// storable-but-wrong SPDI triple, so it is refused as
    /// `UnrepresentableInSpdi` (ruling `spdi-n-unit-repeat-refusal`, #1975).
    #[test]
    fn an_n_unit_repeat_insertion_is_refused() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insN[18]").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "an N-unit repeat names a length, not bases, and must not emit an N-run: {result:?}"
        );
    }

    /// The same refusal on the `delins` arm: `delinsN[341]` must not emit 341
    /// `N`s (this was the `delinsN[341]` corpus row).
    #[test]
    fn an_n_unit_repeat_delins_is_refused() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delinsN[341]").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "an N-unit repeat delins must be refused, not emitted as an N-run: {result:?}"
        );
    }

    /// The ruling is "unit is `N` *or contains `N`*" — a multi-base unit with an
    /// `N` in it (`insAN[3]`) is equally undetermined and equally refused, since
    /// its expansion (`ANANAN`) asserts three `N` bases the input did not spell.
    #[test]
    fn an_n_containing_multibase_repeat_insertion_is_refused() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insAN[3]").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "a repeat unit containing N is undetermined content and must be refused: {result:?}"
        );
    }

    /// An `N`-carrying repeat part inside a compound bracket
    /// (`delins[N[3];A]`) is refused on the same grounds — the guard sits at the
    /// shared expansion leaf, so it reaches bracket parts too.
    #[test]
    fn an_n_unit_repeat_part_in_a_compound_insert_is_refused() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[N[3];A]").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "an N-unit repeat part in a compound insert must be refused: {result:?}"
        );
    }

    /// A short-form tandem repeat spelled with an `N` unit (`g.pos_posN[n]`) is
    /// the same class on the same path and is refused before any reference is
    /// consulted — the refusal is decided from the description alone.
    #[test]
    fn an_n_unit_shortform_repeat_is_refused() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_105N[6]").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "a short-form N-unit repeat must be refused, not expanded to an N-run: {result:?}"
        );
    }

    /// Negative control: the refusal is scoped to *undetermined* content. A
    /// concrete-base repeat (`insACGT[3]`) names its bases exactly and must keep
    /// expanding normally — the guard must not over-reach onto determined units.
    #[test]
    fn a_concrete_base_repeat_insertion_still_expands() {
        let hgvs = parse_hgvs("NC_000001.11:g.100_101insACGT[3]").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ACGTACGTACGT");
    }

    /// The `delins` arm expands an exact repeat insert on the same path. del at
    /// 10..=12 is `CGT` (read from the reference); `insCG[3]` expands to
    /// `CGCGCG`.
    #[test]
    fn an_exact_repeat_delins_expands_its_unit() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delinsCG[3]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "CGCGCG");
    }

    /// A compound insert bracket mixing a literal with a same-reference
    /// coordinate span (`delins[{literal};{start}_{end}]`) is one contiguous
    /// inserted sequence once each part is read out. This is the shape the
    /// original request named — `185_201delins[T;213_271]` — reduced onto the
    /// `ACGT…` contig: del at 10..=12 is `CGT`; the payload is the literal `T`
    /// followed by the span 5..=8 (`ACGT`), so the insertion is `TACGT`.
    #[test]
    fn a_compound_insert_mixing_a_literal_and_a_reference_span_reads_both() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[T;5_8]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "TACGT");
    }

    /// The parts are concatenated in the order written, so swapping them swaps
    /// the resulting bases — `[5_8;T]` is `ACGTT`, not `TACGT`. Pins that the
    /// compound resolver preserves part order rather than sorting or merging.
    #[test]
    fn a_compound_insert_concatenates_its_parts_in_order() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[5_8;T]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "ACGTT");
    }

    /// An inverted span inside a compound bracket reads the reverse complement
    /// of that part only, leaving the surrounding literal untouched. Span 5..=7
    /// is `ACG`, reverse-complemented to `CGT`, so `[A;5_7inv]` is `ACGT`.
    #[test]
    fn a_compound_insert_reverse_complements_an_inverted_span_part() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[A;5_7inv]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "ACGT");
    }

    /// A compound bracket may combine an exact repeat part with a literal; the
    /// repeat expands through the same leaf a bare `insC[3]` uses. `[C[3];A]`
    /// is `CCCA`.
    #[test]
    fn a_compound_insert_expands_an_exact_repeat_part() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[C[3];A]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "CGT");
        assert_eq!(spdi.insertion, "CCCA");
    }

    /// A compound insert on the `ins` arm resolves on the same path as `delins`,
    /// with no deletion. `[T;5_8]` at `g.10_11` inserts `TACGT` after base 10.
    #[test]
    fn a_compound_insertion_reads_on_the_ins_arm_too() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_11ins[T;5_8]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &identity_provider()).unwrap();
        assert_eq!(spdi.position, 10);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "TACGT");
    }

    /// A compound insert whose only undetermined content is a coordinate span
    /// still needs a provider to read that span, so the provider-less path must
    /// decline rather than emit a triple missing those bases.
    #[test]
    fn a_compound_insert_with_a_span_part_needs_a_provider() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[T;5_8]").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::MissingReferenceData { .. })),
            "a coordinate-span part cannot be resolved without a provider: {result:?}"
        );
    }

    /// A part whose bases are genuinely undetermined declines the whole insert.
    /// A non-exact repeat count (`N[10_15]`) inside the bracket names no single
    /// expansion, so even with a provider the compound insert is unsupported.
    #[test]
    fn a_compound_insert_with_an_undetermined_part_is_declined() {
        let hgvs = parse_hgvs("NC_000001.11:g.10_12delins[N[10_15];A]").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::UnsupportedEditType { .. })),
            "a non-exact repeat count part names no single expansion: {result:?}"
        );
    }

    #[test]
    fn an_unspelled_identity_fetches_on_the_non_genomic_axes_too() {
        // The arm is shared by g./m./n./r./c., and the r. path additionally
        // runs the fetched bases through `apply_alphabet(_, Rna)`. Each axis is
        // asserted against its own `del` sibling on the same position, since
        // that sibling is the fetch behavior this arm was made to match.
        let mut provider = MockProvider::new();
        provider.add_genomic_sequence("NR_TEST.1", "ACGTACGTACGTACGTACGTACGTACGT".to_string());
        for (identity, deletion) in [
            ("NR_TEST.1:n.10=", "NR_TEST.1:n.10del"),
            ("NR_TEST.1:r.10=", "NR_TEST.1:r.10del"),
        ] {
            let id_spdi = hgvs_to_spdi(&parse_hgvs(identity).unwrap(), &provider).unwrap();
            let del_spdi = hgvs_to_spdi(&parse_hgvs(deletion).unwrap(), &provider).unwrap();
            assert_eq!(
                (id_spdi.position, id_spdi.deletion.as_str()),
                (del_spdi.position, del_spdi.deletion.as_str()),
                "{identity} must claim the same span `{deletion}` deletes"
            );
            // An identity keeps what it claims; the deletion drops it.
            assert_eq!(
                id_spdi.insertion, id_spdi.deletion,
                "{identity} is an identity"
            );
            assert_eq!(del_spdi.insertion, "", "{deletion} deletes");
        }
    }

    #[test]
    fn an_unspelled_identity_needs_reference_data() {
        // The provider-less path cannot know which bases the span holds, so it
        // reports that rather than emitting a triple whose span is wrong. This
        // matches `g.10del` on the same path.
        let hgvs = parse_hgvs("NC_000001.11:g.10=").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::MissingReferenceData { .. })),
            "expected MissingReferenceData, got {result:?}"
        );
    }

    #[test]
    fn an_out_of_range_unspelled_identity_reports_the_fetch_failure() {
        // The error path of the fetch above. An identity past the end of the
        // contig has no bases to claim, so the fetch fails and that failure is
        // propagated — the same answer `g.9999del` already gives, rather than a
        // panic or a triple invented from an empty span. Before this arm
        // consulted the provider it returned `Ok(9998::)` here, so this also
        // pins that an out-of-range identity is no longer silently accepted.
        let hgvs = parse_hgvs("NC_000001.11:g.9999=").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::MissingReferenceData { .. })),
            "expected MissingReferenceData, got {result:?}"
        );
    }

    #[test]
    fn a_whole_entity_identity_has_no_spdi() {
        // `g.=` asserts the *entire* reference is unchanged and names no
        // interval, so there is no position SPDI could honestly carry. It used
        // to emit `0::`, which `spdi_to_hgvs` reads back as `g.1=` — turning a
        // statement about the whole sequence into one about base 1. Declining
        // is the same answer this module gives every other edit whose shape
        // SPDI cannot encode.
        let hgvs = parse_hgvs("NC_000001.11:g.=").unwrap();
        let result = hgvs_to_spdi(&hgvs, &identity_provider());
        assert!(
            matches!(result, Err(ConversionError::UnsupportedEditType { .. })),
            "expected UnsupportedEditType, got {result:?}"
        );
    }

    #[test]
    fn an_identity_member_does_not_alias_a_sibling_insertion_junction() {
        // The defect this fix exists for. `g.[261_262dup;263=]` is a real
        // normalizer output (5' shuffle, #1321's split spelling). With the
        // identity converting to a zero-width triple, both members landed at
        // interbase 262 — the dup's junction and the identity's empty span —
        // and an applier walking the members cannot tell that apart from two
        // insertions competing for one interbase, so it has to decline the
        // whole description. Giving the identity its real span separates them.
        let provider = identity_provider();
        let variant = parse_hgvs("NC_000001.11:g.[10_11dup;12=]").unwrap();
        let members = match variant {
            HgvsVariant::Allele(allele) => allele.variants,
            other => panic!("expected an allele, got {other}"),
        };
        let triples: Vec<SpdiVariant> = members
            .iter()
            .map(|m| hgvs_to_spdi(m, &provider).expect("member converts"))
            .collect();
        // The dup copies bases 10-11 in at the junction after 11 (interbase 11).
        assert_eq!(triples[0].position, 11);
        assert_eq!(triples[0].deletion, "");
        assert_eq!(triples[0].insertion, "CG");
        // The identity claims base 12 itself: interbase 11..12, not 11..11.
        assert_eq!(triples[1].position, 11);
        assert_eq!(
            triples[1].deletion, "T",
            "the identity must claim its base; a zero-width deletion here is \
             indistinguishable from a second insertion at interbase {}",
            triples[0].position
        );
    }

    #[test]
    fn test_hgvs_to_spdi_simple_cds_requires_provider() {
        // c. variants need transcript metadata to resolve to a transcript
        // position; the simple path therefore returns ProviderRequired.
        let hgvs = parse_hgvs("NM_000088.3:c.100A>G").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::ProviderRequired { .. })
        ));
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("c."), "message should mention c.: {}", msg);
        assert!(
            msg.contains("provider"),
            "message should mention provider: {}",
            msg
        );
    }

    #[test]
    fn test_hgvs_to_spdi_simple_short_form_inversion_requires_provider() {
        // Short-form inversion (no explicit sequence) cannot determine the
        // reference bases without a provider. Pinned audit: the simple path
        // surfaces MissingReferenceData rather than UnsupportedEditType
        // (the prior, pre-#118 behaviour).
        let hgvs = parse_hgvs("NC_000001.11:g.100_200inv").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    // SPDI to HGVS tests

    #[test]
    fn test_spdi_to_hgvs_substitution() {
        let spdi = SpdiVariant::new("NC_000001.11", 12344, "A", "G");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.12345A>G");
    }

    #[test]
    fn test_spdi_to_hgvs_deletion() {
        let spdi = SpdiVariant::deletion("NC_000001.11", 99, "ATG");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_102delATG");
    }

    #[test]
    fn test_spdi_to_hgvs_insertion() {
        let spdi = SpdiVariant::insertion("NC_000001.11", 100, "ATG");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        // SPDI 100 = boundary AFTER 1-based 100 = HGVS g.100_101ins (#390).
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_101insATG");
    }

    #[test]
    fn test_spdi_to_hgvs_delins() {
        let spdi = SpdiVariant::delins("NC_000001.11", 99, "ATG", "TTCC");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_102delinsTTCC");
    }

    #[test]
    fn test_spdi_to_hgvs_identity() {
        let spdi = SpdiVariant::new("NC_000001.11", 99, "A", "A");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100A=");
    }

    #[test]
    fn test_spdi_to_hgvs_single_del() {
        let spdi = SpdiVariant::deletion("NC_000001.11", 99, "A");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100delA");
    }

    // Roundtrip tests

    #[test]
    fn test_roundtrip_substitution() {
        let original = "NC_000001.11:g.12345A>G";
        let hgvs = parse_hgvs(original).unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        let back = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(back.to_string(), original);
    }

    #[test]
    fn test_roundtrip_insertion() {
        let original = "NC_000001.11:g.100_101insATG";
        let hgvs = parse_hgvs(original).unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        let back = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(back.to_string(), original);
    }

    #[test]
    fn test_roundtrip_deletion_with_seq() {
        let original = "NC_000001.11:g.100_102delATG";
        let hgvs = parse_hgvs(original).unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        let back = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(back.to_string(), original);
    }

    #[test]
    fn test_error_display() {
        let err = ConversionError::UnsupportedVariantType {
            description: "test".to_string(),
        };
        assert!(err.to_string().contains("unsupported variant type"));

        let err = ConversionError::MissingReferenceData {
            description: "test".to_string(),
        };
        assert!(err.to_string().contains("missing reference data"));
    }

    // =========================================================================
    // Issue #117: Reference-aware HGVS→SPDI for del/dup/delins
    // =========================================================================
    //
    // These tests exercise the production `hgvs_to_spdi(variant, provider)`
    // path with a real `MockProvider`. They replace the earlier
    // `MockGenomicRef` prototype, which predated the public provider entry
    // point and is now redundant.

    /// Build a `MockProvider` with a contig where:
    ///   1-based 100..102 = "ATG"
    ///   1-based 200..206 = "GATTACA"
    ///   1-based 1000..1009 = "AAACCCGGGT"
    /// All other positions are filled with 'N'.
    fn make_test_genomic_provider() -> crate::reference::mock::MockProvider {
        let mut p = crate::reference::mock::MockProvider::new();
        let mut contig = String::new();
        contig.push_str(&"N".repeat(99)); // 1-based 1..99 (0-based 0..99)
        contig.push_str("ATG"); // 1-based 100..102
        contig.push_str(&"N".repeat(97)); // pad through 1-based 199
        contig.push_str("GATTACA"); // 1-based 200..206
        contig.push_str(&"N".repeat(793)); // pad through 1-based 999
        contig.push_str("AAACCCGGGT"); // 1-based 1000..1009
        contig.push_str(&"N".repeat(50));
        p.add_genomic_sequence("NC_000001.11", &contig);
        p
    }

    #[test]
    fn fetch_reference_bases_returns_genomic_bases() {
        let provider = make_test_genomic_provider();
        let bases = fetch_reference_bases(&provider, "NC_000001.11", 100, 102).unwrap();
        assert_eq!(bases, "ATG");
    }

    #[test]
    fn fetch_reference_bases_errors_when_provider_lacks_contig() {
        let provider = crate::reference::mock::MockProvider::new();
        let err = fetch_reference_bases(&provider, "NC_000099.99", 100, 102).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
        let msg = err.to_string();
        assert!(msg.contains("NC_000099.99"));
        assert!(msg.contains("100"));
        assert!(msg.contains("102"));
    }

    #[test]
    fn fetch_reference_bases_errors_on_short_contig() {
        let mut provider = crate::reference::mock::MockProvider::new();
        // Contig is only 3 bases — fetching 1-based 100..102 must fail.
        provider.add_genomic_sequence("NC_000001.11", "ATG");
        let err = fetch_reference_bases(&provider, "NC_000001.11", 100, 102).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
    }

    #[test]
    fn hgvs_to_spdi_deletion_short_form_with_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NC_000001.11");
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn hgvs_to_spdi_duplication_short_form_with_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102dup").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        // Dup encodes as an SPDI insertion at the 3' end of the duplicated
        // region. SPDI interbase: the position is the 1-based end of
        // the dup region (102), which is the boundary AFTER base 102
        // and matches the equivalent `g.102_103ins…` form (#390).
        assert_eq!(spdi.position, 102);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn hgvs_to_spdi_single_base_duplication_short_form_with_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100dup").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        // Single-base dup: end_one_based = 100, SPDI position = 100 (#390).
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "A");
    }

    #[test]
    fn hgvs_to_spdi_delins_short_form_with_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delinsTTCC").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "TTCC");
    }

    #[test]
    fn hgvs_to_spdi_long_deletion_with_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.1000_1009del").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "AAACCCGGGT");
        assert_eq!(spdi.deletion.len(), 10);
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn hgvs_to_spdi_explicit_deletion_does_not_consult_provider() {
        // When the user supplied an explicit deleted sequence, ferro emits
        // it as-is. Verified by attaching an empty provider — if we
        // consulted it, the call would fail.
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delATG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn hgvs_to_spdi_explicit_duplication_does_not_consult_provider() {
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102dupATG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        // SPDI interbase position 102 = boundary AFTER 1-based 102 (#390).
        assert_eq!(spdi.position, 102);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn hgvs_to_spdi_substitution_unaffected_by_provider() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.12345A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.to_string(), "NC_000001.11:12344:A:G");
    }

    #[test]
    fn hgvs_to_spdi_mnv_delins_with_provider_round_trips() {
        // Same-length delins should round-trip through SPDI.
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102delinsGGG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "GGG");
        let back = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(back.to_string(), "NC_000001.11:g.100_102delinsGGG");
    }

    #[test]
    fn hgvs_to_spdi_deletion_round_trip_with_provider() {
        let provider = make_test_genomic_provider();
        let original = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
        let spdi = hgvs_to_spdi(&original, &provider).unwrap();
        let back = spdi_to_hgvs(&spdi).unwrap();
        // SPDI carries the deleted sequence, so the recovered HGVS is the
        // explicit form.
        assert_eq!(back.to_string(), "NC_000001.11:g.100_102delATG");
    }

    #[test]
    fn hgvs_to_spdi_delins_round_trip_with_provider() {
        let provider = make_test_genomic_provider();
        let original = parse_hgvs("NC_000001.11:g.100_102delinsTTCC").unwrap();
        let spdi = hgvs_to_spdi(&original, &provider).unwrap();
        let back = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(back.to_string(), "NC_000001.11:g.100_102delinsTTCC");
    }

    #[test]
    fn hgvs_to_spdi_dup_round_trip_emits_ins_form_via_reference_free_path() {
        // HGVS dup → SPDI ins, with the duplicated bases populated from
        // the provider. Without a reference-aware SPDI→HGVS direction the
        // reverse path produces ins form (per the SPDI-as-canonical
        // contract). PR #119 (sibling) adds `spdi_to_hgvs_with_ref` that
        // recovers the dup form when the 5' flank matches.
        let provider = make_test_genomic_provider();
        let original = parse_hgvs("NC_000001.11:g.100_102dup").unwrap();
        let spdi = hgvs_to_spdi(&original, &provider).unwrap();
        // Post-#390: SPDI position = end_one_based (102), matching the
        // equivalent `g.102_103ins` interbase boundary.
        assert_eq!(spdi.position, 102);
        assert_eq!(spdi.insertion, "ATG");
        let recovered = spdi_to_hgvs(&spdi).unwrap();
        // SPDI 102 = boundary AFTER 1-based 102 = HGVS g.102_103ins.
        assert_eq!(recovered.to_string(), "NC_000001.11:g.102_103insATG");
    }

    #[test]
    fn hgvs_to_spdi_mito_short_form_deletion_with_provider() {
        // Mito accession (NC_012920.1) is genomic; verify the same path
        // works there.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut seq = "N".repeat(16559);
        seq.push_str("GATC"); // 1-based 16560..16563
        seq.push_str(&"N".repeat(20));
        provider.add_genomic_sequence("NC_012920.1", &seq);
        let hgvs = parse_hgvs("NC_012920.1:m.16560_16563del").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "GATC");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn hgvs_to_spdi_deletion_with_provider_missing_data() {
        // Provider attached but has no data for the requested contig.
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("NC_000001.11"));
    }

    #[test]
    fn hgvs_to_spdi_simple_pins_existing_short_form_failures() {
        // The simple (no-provider) entry point continues to err on the
        // three short-form cases, matching the existing audit pin.
        for input in [
            "NC_000001.11:g.100_102del",
            "NC_000001.11:g.100_102dup",
            "NC_000001.11:g.100_102delinsTTCC",
        ] {
            let hgvs = parse_hgvs(input).unwrap();
            let r = hgvs_to_spdi_simple(&hgvs);
            assert!(
                matches!(r, Err(ConversionError::MissingReferenceData { .. })),
                "expected MissingReferenceData for {} (got {:?})",
                input,
                r
            );
        }
    }

    #[test]
    fn hgvs_to_spdi_short_form_is_idempotent() {
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102del").unwrap();
        let a = hgvs_to_spdi(&hgvs, &provider).unwrap();
        let b = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(a.to_string(), b.to_string());
    }

    // =========================================================================
    // P3: SPDI edge case tests
    // =========================================================================

    #[test]
    fn test_spdi_empty_deletion_insertion() {
        // Pure insertion has empty deletion
        let spdi = SpdiVariant::insertion("NC_000001.11", 100, "ATG");
        assert!(spdi.is_insertion());
        assert!(!spdi.is_deletion());
        assert!(!spdi.is_identity());
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_spdi_empty_insertion_deletion() {
        // Pure deletion has empty insertion
        let spdi = SpdiVariant::deletion("NC_000001.11", 100, "ATG");
        assert!(spdi.is_deletion());
        assert!(!spdi.is_insertion());
        assert!(!spdi.is_identity());
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn test_spdi_both_empty_is_identity() {
        // Both empty is identity at position (unusual but valid)
        let spdi = SpdiVariant::new("NC_000001.11", 100, "", "");
        assert!(spdi.is_identity());
        assert!(!spdi.is_insertion());
        assert!(!spdi.is_deletion());
    }

    #[test]
    fn test_spdi_single_base_insertion() {
        let spdi = SpdiVariant::insertion("NC_000001.11", 100, "A");
        assert!(spdi.is_insertion());
        assert_eq!(spdi.insertion.len(), 1);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("ins"));
    }

    #[test]
    fn test_spdi_single_base_deletion() {
        let spdi = SpdiVariant::deletion("NC_000001.11", 100, "A");
        assert!(spdi.is_deletion());
        assert_eq!(spdi.deletion.len(), 1);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("del"));
    }

    #[test]
    fn test_spdi_long_insertion_100bp() {
        // Test 100bp insertion (common structural variant size)
        let long_seq = "A".repeat(100);
        let spdi = SpdiVariant::insertion("NC_000001.11", 12345, &long_seq);

        assert!(spdi.is_insertion());
        assert_eq!(spdi.insertion.len(), 100);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("ins"));
        // Verify the sequence is preserved
        assert!(hgvs.to_string().ends_with(&format!("ins{}", long_seq)));
    }

    #[test]
    fn test_spdi_long_deletion_100bp() {
        // Test 100bp deletion
        let long_seq = "ACGT".repeat(25); // 100bp
        let spdi = SpdiVariant::deletion("NC_000001.11", 12345, &long_seq);

        assert!(spdi.is_deletion());
        assert_eq!(spdi.deletion.len(), 100);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("del"));
    }

    #[test]
    fn test_spdi_long_indel_asymmetric() {
        // Delete 50bp, insert 150bp (net +100bp)
        let del_seq = "A".repeat(50);
        let ins_seq = "G".repeat(150);
        let spdi = SpdiVariant::delins("NC_000001.11", 12345, &del_seq, &ins_seq);

        assert!(!spdi.is_insertion());
        assert!(!spdi.is_deletion());
        assert_eq!(spdi.deletion.len(), 50);
        assert_eq!(spdi.insertion.len(), 150);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("delins"));
    }

    #[test]
    fn test_spdi_very_long_insertion_1000bp() {
        // Test 1000bp insertion (larger structural variant)
        let long_seq = "ACGT".repeat(250); // 1000bp
        let spdi = SpdiVariant::insertion("NC_000001.11", 50000, &long_seq);

        assert!(spdi.is_insertion());
        assert_eq!(spdi.insertion.len(), 1000);

        // Should still convert to HGVS
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("ins"));
    }

    #[test]
    fn test_spdi_position_zero() {
        // Position 0 is valid in SPDI (0-based)
        let spdi = SpdiVariant::new("NC_000001.11", 0, "A", "G");
        assert_eq!(spdi.position, 0);

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        // HGVS position should be 1 (1-based)
        assert!(hgvs.to_string().contains("g.1A>G"));
    }

    #[test]
    fn test_spdi_position_max() {
        // Very large position (near chromosome end)
        let spdi = SpdiVariant::new("NC_000001.11", 248956421, "A", "G");

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("248956422")); // 1-based
    }

    #[test]
    fn test_spdi_lowercase_sequence() {
        // SPDI should handle lowercase (though uppercase is standard)
        let spdi = SpdiVariant::new("NC_000001.11", 100, "a", "g");

        // The variant should work even with lowercase
        assert_eq!(spdi.deletion, "a");
        assert_eq!(spdi.insertion, "g");
    }

    #[test]
    fn test_spdi_mixed_case_sequence() {
        // Mixed case sequence
        let spdi = SpdiVariant::new("NC_000001.11", 100, "AtGc", "GcTa");

        assert_eq!(spdi.deletion, "AtGc");
        assert_eq!(spdi.insertion, "GcTa");
    }

    #[test]
    fn test_spdi_n_bases_in_sequence() {
        // N (unknown) bases in sequence
        let spdi = SpdiVariant::new("NC_000001.11", 100, "ANG", "TNC");

        assert_eq!(spdi.deletion, "ANG");
        assert_eq!(spdi.insertion, "TNC");
    }

    #[test]
    fn test_spdi_complex_repeat_sequence() {
        // Repeat sequence (e.g., microsatellite)
        let repeat = "CAG".repeat(30); // 90bp CAG repeat
        let spdi = SpdiVariant::insertion("NC_000004.12", 3074876, &repeat);

        assert!(spdi.is_insertion());
        assert_eq!(spdi.insertion.len(), 90);
    }

    #[test]
    fn test_spdi_to_hgvs_delins_single_base_del() {
        // Single base deletion with multi-base insertion
        let spdi = SpdiVariant::delins("NC_000001.11", 100, "A", "TTTT");

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        // Single base del + ins = delins at single position
        assert!(hgvs.to_string().contains("delinsTTTT"));
    }

    #[test]
    fn test_spdi_to_hgvs_delins_single_base_ins() {
        // Multi-base deletion with single base insertion
        let spdi = SpdiVariant::delins("NC_000001.11", 100, "AAAA", "T");

        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert!(hgvs.to_string().contains("delinsT"));
    }

    #[test]
    fn test_spdi_different_chromosome_formats() {
        // Various accession formats should work
        let test_cases = vec![
            ("NC_000001.11", "NC_000001.11"), // Standard RefSeq
            ("NC_000023.11", "NC_000023.11"), // X chromosome
            ("NC_000024.10", "NC_000024.10"), // Y chromosome
            ("NC_012920.1", "NC_012920.1"),   // Mitochondrial
        ];

        for (input_acc, expected_acc) in test_cases {
            let spdi = SpdiVariant::new(input_acc, 100, "A", "G");
            assert_eq!(spdi.sequence, expected_acc);

            let hgvs = spdi_to_hgvs(&spdi).unwrap();
            assert!(hgvs.to_string().starts_with(expected_acc));
        }
    }

    #[test]
    fn test_spdi_roundtrip_preserves_case_normalized() {
        // Create SPDI substitution (SNV) which roundtrips cleanly
        let spdi = SpdiVariant::new("NC_000001.11", 100, "A", "G");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        let back = hgvs_to_spdi_simple(&hgvs).unwrap();

        // Should preserve the sequence
        assert_eq!(back.deletion, "A");
        assert_eq!(back.insertion, "G");

        // Test multi-base delins - without reference data, the roundtrip
        // cannot reconstruct the deletion sequence and returns an error
        let spdi_delins = SpdiVariant::new("NC_000001.11", 100, "ACGT", "TGCA");
        let hgvs_delins = spdi_to_hgvs(&spdi_delins).unwrap();
        let back_delins = hgvs_to_spdi_simple(&hgvs_delins);

        // Without reference, this should fail since the deletion sequence is unknown
        assert!(back_delins.is_err());
    }

    #[test]
    fn test_spdi_empty_seq_insertion_roundtrip() {
        // Empty deletion (pure insertion) roundtrip
        let spdi = SpdiVariant::insertion("NC_000001.11", 100, "ATG");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();

        // HGVS format for insertion is pos_pos+1insX
        assert!(hgvs.to_string().contains("ins"));

        // Roundtrip back
        let back = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(back.deletion, "");
        assert_eq!(back.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_various_accession_types() {
        // Test conversion from various accession types
        let test_variants = vec![
            "NC_000001.11:g.12345A>G", // Chromosome
            "NC_000023.11:g.12345A>G", // X chromosome
            "NC_012920.1:g.12345A>G",  // Mitochondrial
        ];

        for variant_str in test_variants {
            let hgvs = parse_hgvs(variant_str).unwrap();
            let spdi = hgvs_to_spdi_simple(&hgvs);
            assert!(spdi.is_ok(), "Failed for: {}", variant_str);
        }
    }

    #[test]
    fn test_spdi_display_format() {
        let spdi = SpdiVariant::new("NC_000001.11", 12344, "A", "G");
        assert_eq!(spdi.to_string(), "NC_000001.11:12344:A:G");

        let spdi_del = SpdiVariant::deletion("NC_000001.11", 100, "ATG");
        assert_eq!(spdi_del.to_string(), "NC_000001.11:100:ATG:");

        let spdi_ins = SpdiVariant::insertion("NC_000001.11", 100, "ATG");
        assert_eq!(spdi_ins.to_string(), "NC_000001.11:100::ATG");
    }

    #[test]
    fn test_spdi_identity_various_lengths() {
        // Single base identity
        let spdi1 = SpdiVariant::new("NC_000001.11", 100, "A", "A");
        assert!(spdi1.is_identity());

        // Multi-base identity (unusual but valid)
        let spdi2 = SpdiVariant::new("NC_000001.11", 100, "ATG", "ATG");
        assert!(spdi2.is_identity());

        // Empty identity
        let spdi3 = SpdiVariant::new("NC_000001.11", 100, "", "");
        assert!(spdi3.is_identity());
    }

    // =========================================================================
    // Issue #119: SPDI→HGVS dup recovery
    // =========================================================================

    /// Build a MockProvider with a single genomic sequence registered for
    /// `NC_000001.11`. The string `seq` is the full contig sequence, indexed
    /// from 0-based position 0.
    fn provider_with_genomic(seq: &str) -> crate::reference::mock::MockProvider {
        let mut p = crate::reference::mock::MockProvider::new();
        p.add_genomic_sequence("NC_000001.11", seq);
        p
    }

    #[test]
    fn spdi_to_hgvs_with_ref_recovers_multi_base_dup() {
        // Reference: positions 1-based 100..102 = "ATG"
        // Build a contig where 0-based offsets 99, 100, 101 = 'A', 'T', 'G'
        // We pad with 'N' before and after so the reference fetch works.
        let mut contig = "N".repeat(99);
        contig.push_str("ATG"); // 0-based 99..102 (1-based 100..102)
        contig.push_str(&"N".repeat(50));
        let provider = provider_with_genomic(&contig);

        // SPDI 102::ATG is the canonical SPDI form of g.100_102dupATG
        // under the interbase-correct convention (#390): the insertion
        // sits at the boundary AFTER 1-based base 102.
        let spdi = SpdiVariant::insertion("NC_000001.11", 102, "ATG");

        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_102dupATG");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_recovers_single_base_dup() {
        // 1-based base 100 = 'A' → SPDI insertion at 100::A is a single-base dup.
        let mut contig = "N".repeat(99);
        contig.push('A'); // 0-based 99 = 1-based 100
        contig.push_str(&"N".repeat(20));
        let provider = provider_with_genomic(&contig);

        // g.100dupA → SPDI 100::A under the interbase-correct
        // convention (#390); SPDI position 100 sits AFTER 1-based 100,
        // and the 5' flank base 1-based 100 = 'A' matches the
        // inserted 'A'.
        let spdi = SpdiVariant::insertion("NC_000001.11", 100, "A");

        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100dupA");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_keeps_ins_when_no_match() {
        // 5' flank of length 3 ending at SPDI position 102 (under the
        // post-#390 interbase convention) = 1-based bases 100..102 =
        // "CCC" — does NOT equal the inserted "ATG".
        let mut contig = "N".repeat(99);
        contig.push_str("CCC"); // 1-based 100..102 = "CCC"
        contig.push_str(&"N".repeat(20));
        let provider = provider_with_genomic(&contig);

        let spdi = SpdiVariant::insertion("NC_000001.11", 102, "ATG");

        // Should fall through to ins-form. spdi_to_hgvs renders an
        // insertion as `g.{pos}_{pos+1}insATG` where `pos` is the
        // SPDI 0-based interbase position itself (#390): SPDI 102 →
        // g.102_103insATG.
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.102_103insATG");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_rejects_ins_at_contig_start() {
        // SPDI position 0 with a 3-base insertion: there are no
        // preceding bases at all, and HGVS has no standard notation
        // for "insert before the first base" (#390). The conversion
        // surfaces `InvalidPosition` rather than silently emitting
        // `g.1_2insATG` (which mis-represents the actual insertion
        // point).
        let provider = provider_with_genomic("ATGCATGCATGC");

        let spdi = SpdiVariant::insertion("NC_000001.11", 0, "ATG");
        let err = spdi_to_hgvs_with_ref(&spdi, &provider).expect_err(
            "SPDI position 0 (insertion before contig start) must surface InvalidPosition",
        );
        assert!(matches!(err, ConversionError::InvalidPosition { .. }));
    }

    #[test]
    fn spdi_to_hgvs_with_ref_substitution_unchanged() {
        let provider = provider_with_genomic(&"N".repeat(20000));
        let spdi = SpdiVariant::new("NC_000001.11", 12344, "A", "G");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.12345A>G");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_deletion_unchanged() {
        let provider = provider_with_genomic(&"N".repeat(2000));
        let spdi = SpdiVariant::deletion("NC_000001.11", 99, "ATG");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_102delATG");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_delins_unchanged() {
        let provider = provider_with_genomic(&"N".repeat(2000));
        let spdi = SpdiVariant::delins("NC_000001.11", 99, "ATG", "TTCC");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100_102delinsTTCC");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_identity_unchanged() {
        let provider = provider_with_genomic(&"N".repeat(2000));
        let spdi = SpdiVariant::new("NC_000001.11", 99, "A", "A");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100A=");
    }

    /// A zero-width triple is an identity by the predicate (`deletion ==
    /// insertion`) but names no bases, so the conversion arm must refuse it
    /// rather than emit `g.100=` over a base the triple never claimed.
    ///
    /// Asserted on **both** public entry points: `spdi_to_hgvs_with_ref`
    /// delegates to `spdi_to_hgvs` for its base conversion, so the refusal
    /// reaches it too — and a future cut that stopped delegating would silently
    /// lose the guard on the reference-aware path.
    #[test]
    fn zero_width_identity_is_refused_on_both_entry_points() {
        let spdi = SpdiVariant::new("NC_000001.11", 99, "", "");
        assert!(spdi.is_identity(), "both sides empty is an identity");
        assert!(
            matches!(
                spdi_to_hgvs(&spdi),
                Err(ConversionError::UnsupportedEditType { .. })
            ),
            "a triple naming zero bases must not convert to an identity"
        );
        let provider = provider_with_genomic(&"N".repeat(2000));
        assert!(
            matches!(
                spdi_to_hgvs_with_ref(&spdi, &provider),
                Err(ConversionError::UnsupportedEditType { .. })
            ),
            "the reference-aware path must inherit the refusal"
        );
    }

    /// A one-base identity still converts — the guard must be scoped to the
    /// zero-width case and not have cost the arm its ordinary behaviour.
    #[test]
    fn a_one_base_identity_still_converts() {
        let spdi = SpdiVariant::new("NC_000001.11", 99, "A", "A");
        let hgvs = spdi_to_hgvs(&spdi).expect("a one-base identity converts");
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.100A=");
    }

    #[test]
    fn spdi_to_hgvs_with_ref_propagates_ref_error() {
        // MockProvider with NO genomic_sequences registered for the
        // requested accession. The fetch returns
        // FerroError::GenomicReferenceNotAvailable for get_genomic_sequence
        // AND no transcript by that name for get_sequence. Both fail, so
        // the helper should return ConversionError::MissingReferenceData.
        let provider = crate::reference::mock::MockProvider::new();
        let spdi = SpdiVariant::insertion("NC_000999.99", 101, "ATG");

        let result = spdi_to_hgvs_with_ref(&spdi, &provider);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    // =========================================================================
    // Issue #116: c./n./r./m. coordinate-system support
    // =========================================================================

    use crate::reference::mock::MockProvider;
    use crate::reference::transcript::{Exon, GenomeBuild, ManeStatus, Strand};

    /// Build a small test transcript covering enough cases for c./n./r. tests:
    /// - 5'UTR length 5 (positions 1-5 in tx)
    /// - CDS  length 30 (tx positions 6-35; cds_start=6, cds_end=35)
    /// - 3'UTR length 5 (tx positions 36-40)
    ///
    /// Single exon over the full transcript so the simple no-gap path applies.
    fn make_test_provider() -> MockProvider {
        let tx = Transcript::new(
            "NM_TEST.1".to_string(),
            Some("TEST".to_string()),
            Strand::Plus,
            // 40 bases: 5 (UTR5) + 30 (CDS) + 5 (UTR3)
            "AAAAATGCCCAAAGGGTTTAGGCCCAAAGGGTTATAAA".to_string() + "AA",
            Some(6),
            Some(35),
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        provider
    }

    /// Build a multi-exon transcript suitable for testing intronic resolution
    /// rejections. Exon 1: tx 1-50, Exon 2: tx 51-100; CDS tx 11-90.
    fn make_intronic_provider() -> MockProvider {
        let tx = Transcript::new(
            "NM_INTRON.1".to_string(),
            Some("INTRON".to_string()),
            Strand::Plus,
            "A".repeat(100),
            Some(11),
            Some(90),
            vec![Exon::new(1, 1, 50), Exon::new(2, 51, 100)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        provider
    }

    // ----- r.*N / c.*N 3'UTR agreement (#944) --------------------------------

    /// #944: r.*N and c.*N denote the same 3'UTR transcript position, so both
    /// must resolve to the same SPDI position. `resolve_rna_pos` now routes the
    /// 3'UTR case through the same `CoordinateMapper::cds_to_tx` the c.*N path
    /// uses (previously it short-circuited with its own `cds_end + base`), so
    /// one conversion answers both spellings.
    #[test]
    fn r_star_and_c_star_resolve_to_same_spdi_position() {
        let provider = make_test_provider();
        // NM_TEST.1: cds_end = tx 35, so *1 is tx 36 (1-based) → SPDI 0-based 35.
        let c = parse_hgvs("NM_TEST.1:c.*1del").unwrap();
        let r = parse_hgvs("NM_TEST.1:r.*1del").unwrap();
        let c_spdi = hgvs_to_spdi(&c, &provider).unwrap();
        let r_spdi = hgvs_to_spdi(&r, &provider).unwrap();
        assert_eq!(
            c_spdi.position, r_spdi.position,
            "c.*1 and r.*1 must resolve to the same SPDI position"
        );
        assert_eq!(c_spdi.position, 35);
    }

    /// Build a transcript whose 3'UTR lives in a *separate exon across a
    /// tx-coordinate gap*, so the `r.` and `c.` arms only agree if both take
    /// the same route:
    ///
    /// - Exon 1: tx 1..35 (5'UTR tx 1-5, CDS tx 6-35; `cds_end` = 35 is the
    ///   last base of exon 1).
    /// - Gap in the exon table: tx 36..39 are covered by no exon (cdot-style
    ///   alignment gap — `exon1.end + 1 (36) != exon2.start (40)`). The stored
    ///   sequence is 44 bases, so those four bases DO exist on the transcript;
    ///   what they lack is a genomic counterpart.
    /// - Exon 2: tx 40..44.
    ///
    /// **#1619 decided which of those bases `*1` names, and it is tx 36.** The
    /// `c.`/`n.`/`r.` axis counts the transcript's own bases
    /// (`background/numbering.md:21`, `:52`), so `c.*1` is `cds_end + 1` on the
    /// flat sequence. This fixture used to pin the opposite — the exon walk,
    /// which skipped the four unaligned bases and answered tx 40 — and the doc
    /// here called tx 36 "a nonexistent coordinate", which is the mistaken
    /// premise the ruling `c-and-n-positions-are-flat-transcript-offsets`
    /// overturns.
    ///
    /// The fixture stays, because the property it was built for is still the
    /// live one and is still non-vacuous here: `r.*N` and `c.*N` must resolve
    /// identically (#944), and on a single-exon transcript the two routes
    /// coincide so any test there would pass either way.
    fn make_gapped_utr3_provider() -> MockProvider {
        let tx = Transcript::new(
            "NM_GAP.1".to_string(),
            Some("GAP".to_string()),
            Strand::Plus,
            "A".repeat(44),
            Some(6),
            Some(35),
            vec![Exon::new(1, 1, 35), Exon::new(2, 40, 44)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        provider
    }

    /// #944 (non-vacuous): on a transcript whose 3'UTR sits in a separate exon
    /// across a tx-coordinate gap, r.*1 and c.*1 must STILL resolve to the same
    /// SPDI position — the property #944 is about, and one a single-exon
    /// fixture cannot test because both routes coincide there.
    ///
    /// #1619 fixes WHICH position that is: `*1` is `cds_end + 1` on the flat
    /// transcript (tx 36 → SPDI 35), not the exon walk's tx 40.
    #[test]
    fn r_star_c_star_agree_across_exon_gap() {
        let provider = make_gapped_utr3_provider();
        // cds_end = tx 35, so *1 is tx 36 → SPDI 0-based 35. tx 36-39 are
        // transcript bases the exon table does not cover; `c.*N` counts them.
        let c = parse_hgvs("NM_GAP.1:c.*1A>G").unwrap();
        let r = parse_hgvs("NM_GAP.1:r.*1a>g").unwrap();
        let c_spdi = hgvs_to_spdi(&c, &provider).unwrap();
        let r_spdi = hgvs_to_spdi(&r, &provider).unwrap();
        assert_eq!(
            c_spdi.position, r_spdi.position,
            "c.*1 and r.*1 must resolve to the same SPDI position across the exon gap"
        );
        assert_eq!(
            c_spdi.position, 35,
            "*1 is cds_end + 1 on the flat transcript (tx 36 → SPDI 35); the exon \
             walk this replaced skipped the tx 36-39 bases and answered SPDI 39 (#1619)"
        );
    }

    /// A 3'UTR r.*N on a non-coding transcript (no CDS end) still declines
    /// cleanly rather than mapping through a missing anchor.
    #[test]
    fn r_star_on_non_coding_transcript_declines() {
        let mut provider = MockProvider::new();
        let tx = Transcript::new(
            "NR_TEST.1".to_string(),
            Some("NCTEST".to_string()),
            Strand::Plus,
            "A".repeat(40),
            None,
            None,
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        provider.add_transcript(tx);
        let r = parse_hgvs("NR_TEST.1:r.*1del").unwrap();
        assert!(hgvs_to_spdi(&r, &provider).is_err());
    }

    // ----- r.-N / c.-N 5'UTR agreement (#960) --------------------------------

    /// #960: r.-N and c.-N denote the same 5'UTR transcript position, so both
    /// must resolve to the same SPDI position. `resolve_rna_pos` now routes the
    /// 5'UTR case through the same `CoordinateMapper::cds_to_tx` the c.-N path
    /// uses (previously it fell through to `ensure_positive_tx` and was
    /// rejected as a non-positive base).
    #[test]
    fn r_minus_and_c_minus_resolve_to_same_spdi_position() {
        let provider = make_test_provider();
        // NM_TEST.1: cds_start = tx 6, so c.-3 / r.-3 is tx 3 (1-based) → SPDI 2.
        let c = parse_hgvs("NM_TEST.1:c.-3del").unwrap();
        let r = parse_hgvs("NM_TEST.1:r.-3del").unwrap();
        let c_spdi = hgvs_to_spdi(&c, &provider).unwrap();
        let r_spdi = hgvs_to_spdi(&r, &provider).unwrap();
        assert_eq!(
            c_spdi.position, r_spdi.position,
            "c.-3 and r.-3 must resolve to the same SPDI position"
        );
        assert_eq!(c_spdi.position, 2);
    }

    /// Build a transcript whose 5'UTR straddles a *tx-coordinate gap*, so the
    /// `r.` and `c.` arms only agree if both take the same route:
    ///
    /// - Exon 1: tx 1..5 — the upstream part of the 5'UTR.
    /// - Gap in the exon table: tx 6..9 are covered by no exon (`exon1.end + 1
    ///   (6) != exon2.start (10)`). The stored sequence is 44 bases, so those
    ///   four are transcript bases with no genomic counterpart.
    /// - Exon 2: tx 10..44 — 5'UTR tx 10-11 then CDS from `cds_start` = tx 12.
    ///
    /// **#1619 decided which base `c.-3` names, and it is tx 9** — three bases
    /// 5' of `cds_start` on the flat transcript. This fixture used to pin the
    /// exon walk's tx 5 and called tx 9 "inside the nonexistent gap"; the
    /// ruling `c-and-n-positions-are-flat-transcript-offsets` overturns that
    /// premise. The fixture stays because the #960 property — `r.-N` and `c.-N`
    /// resolving identically — is still live and still untestable on a
    /// single-exon transcript, where the two routes coincide.
    fn make_gapped_utr5_provider() -> MockProvider {
        let tx = Transcript::new(
            "NM_GAP5.1".to_string(),
            Some("GAP5".to_string()),
            Strand::Plus,
            "A".repeat(44),
            Some(12),
            Some(40),
            vec![Exon::new(1, 1, 5), Exon::new(2, 10, 44)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        provider
    }

    /// #960 (non-vacuous): on a transcript whose 5'UTR straddles a tx-coordinate
    /// gap, r.-3 and c.-3 must STILL resolve to the same SPDI position — the
    /// property #960 is about, and one a single-exon fixture cannot test.
    ///
    /// #1619 fixes WHICH position that is: `c.-3` is `cds_start - 3` on the
    /// flat transcript (tx 9 → SPDI 8), not the exon walk's tx 5.
    #[test]
    fn r_minus_c_minus_agree_across_exon_gap() {
        let provider = make_gapped_utr5_provider();
        // cds_start = tx 12, so c.-3 / r.-3 is tx 9 → SPDI 0-based 8. tx 6-9 are
        // transcript bases the exon table does not cover; `c.-N` counts them.
        let c = parse_hgvs("NM_GAP5.1:c.-3A>G").unwrap();
        let r = parse_hgvs("NM_GAP5.1:r.-3a>g").unwrap();
        let c_spdi = hgvs_to_spdi(&c, &provider).unwrap();
        let r_spdi = hgvs_to_spdi(&r, &provider).unwrap();
        assert_eq!(
            c_spdi.position, r_spdi.position,
            "c.-3 and r.-3 must resolve to the same SPDI position across the exon gap"
        );
        assert_eq!(
            c_spdi.position, 8,
            "-3 is cds_start - 3 on the flat transcript (tx 9 → SPDI 8); the exon \
             walk this replaced skipped the tx 6-9 bases and answered SPDI 4 (#1619)"
        );
    }

    /// A 5'UTR r.-N on a non-coding transcript (no CDS start) declines cleanly
    /// rather than mapping through a missing anchor.
    #[test]
    fn r_minus_on_non_coding_transcript_declines() {
        let mut provider = MockProvider::new();
        let tx = Transcript::new(
            "NR_TEST5.1".to_string(),
            Some("NCTEST5".to_string()),
            Strand::Plus,
            "A".repeat(40),
            None,
            None,
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        provider.add_transcript(tx);
        let r = parse_hgvs("NR_TEST5.1:r.-3del").unwrap();
        assert!(hgvs_to_spdi(&r, &provider).is_err());
    }

    // ----- r.*N / c.*N 3' upper bound (#962) ---------------------------------

    /// #962 boundary: the last 3'UTR base still resolves. NM_TEST.1 has tx length
    /// 40 with the 3'UTR at tx 36-40, so `*5` = tx 40 (the final base) — c.*5 and
    /// r.*5 must both succeed and agree at SPDI 0-based 39. Guards the upper-bound
    /// check against off-by-one over-rejection of the last valid position.
    #[test]
    fn r_star_and_c_star_at_last_base_resolve() {
        let provider = make_test_provider();
        let c = parse_hgvs("NM_TEST.1:c.*5del").unwrap();
        let r = parse_hgvs("NM_TEST.1:r.*5del").unwrap();
        let c_spdi = hgvs_to_spdi(&c, &provider).unwrap();
        let r_spdi = hgvs_to_spdi(&r, &provider).unwrap();
        assert_eq!(
            c_spdi.position, r_spdi.position,
            "c.*5 and r.*5 (last transcript base) must resolve to the same SPDI position"
        );
        assert_eq!(c_spdi.position, 39);
    }

    /// #962: a `*N` position past the transcript 3' end is declined (not emitted
    /// as an off-sequence SPDI coordinate), for both c.*N and r.*N, and they
    /// agree in declining. On NM_TEST.1 (tx length 40, 3'UTR ends at *5 = tx 40),
    /// `*6` = tx 41 is one base past the end. Before #962 the resolver only guarded
    /// the lower bound, so `*6` mapped to a nonexistent tx 41 → SPDI 40.
    #[test]
    fn r_star_and_c_star_past_end_both_decline() {
        let provider = make_test_provider();
        let c = parse_hgvs("NM_TEST.1:c.*6del").unwrap();
        let r = parse_hgvs("NM_TEST.1:r.*6del").unwrap();
        assert!(
            hgvs_to_spdi(&c, &provider).is_err(),
            "c.*6 is one base past the transcript 3' end and must decline"
        );
        assert!(
            hgvs_to_spdi(&r, &provider).is_err(),
            "r.*6 is one base past the transcript 3' end and must decline"
        );
        // Far past the end declines just as cleanly.
        let c_far = parse_hgvs("NM_TEST.1:c.*99999del").unwrap();
        let r_far = parse_hgvs("NM_TEST.1:r.*99999del").unwrap();
        assert!(hgvs_to_spdi(&c_far, &provider).is_err());
        assert!(hgvs_to_spdi(&r_far, &provider).is_err());
    }

    // ----- m. (mitochondrial) ------------------------------------------------

    #[test]
    fn test_hgvs_to_spdi_simple_mt_substitution() {
        // m. uses NC_012920.1, which is itself a genomic accession.
        let hgvs = parse_hgvs("NC_012920.1:m.3243A>G").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.sequence, "NC_012920.1");
        assert_eq!(spdi.position, 3242);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
        assert_eq!(spdi.to_string(), "NC_012920.1:3242:A:G");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_mt_insertion() {
        let hgvs = parse_hgvs("NC_012920.1:m.100_101insATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI interbase 100 = boundary AFTER 1-based 100 (#390).
        assert_eq!(spdi.position, 100);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_mt_deletion_with_seq() {
        let hgvs = parse_hgvs("NC_012920.1:m.3243_3245delAGG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 3242);
        assert_eq!(spdi.deletion, "AGG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_mt_deletion_without_seq_needs_ref() {
        // Without an explicit deleted sequence, the simple path can't supply
        // the SPDI deletion field — same as g.
        let hgvs = parse_hgvs("NC_012920.1:m.3243_3245del").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    #[test]
    fn dup_hgvs_to_spdi_to_hgvs_with_ref_roundtrip_multi_base() {
        // Build a contig with 1-based 100..102 = "ATG"
        let mut contig = "N".repeat(99);
        contig.push_str("ATG");
        contig.push_str(&"N".repeat(20));
        let provider = provider_with_genomic(&contig);

        // Forward: HGVS dup → SPDI ins (interbase position 102 #390)
        let original = "NC_000001.11:g.100_102dupATG";
        let hgvs = parse_hgvs(original).unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.to_string(), "NC_000001.11:102::ATG");

        // Reverse with reference: SPDI ins → HGVS dup
        let recovered = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(recovered.to_string(), original);
    }

    #[test]
    fn dup_hgvs_to_spdi_to_hgvs_with_ref_roundtrip_single_base() {
        let mut contig = "N".repeat(99);
        contig.push('A');
        contig.push_str(&"N".repeat(20));
        let provider = provider_with_genomic(&contig);

        let original = "NC_000001.11:g.100dupA";
        let hgvs = parse_hgvs(original).unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI interbase 100 (#390): boundary AFTER 1-based 100.
        assert_eq!(spdi.to_string(), "NC_000001.11:100::A");

        let recovered = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        assert_eq!(recovered.to_string(), original);
    }

    #[test]
    fn spdi_to_hgvs_with_ref_does_not_false_detect_non_tandem_insertion() {
        // Spec FAQ: ATCGATCGATCG-A-GGGTCCC → ATCGATCGATCG-A-ATCGATCGATCG-GGGTCCC.
        // The 12-base ATCGATCGATCG sequence appears in the reference at
        // 1-based 1..12, but the insertion point (between 1-based 13 and 14,
        // i.e., SPDI position 13) has a 5' flank "TCGATCGATCGA" — NOT
        // matching the inserted "ATCGATCGATCG". Per the spec FAQ this MUST
        // remain ins.
        let contig = "ATCGATCGATCGAGGGTCCC".to_string();
        let provider = provider_with_genomic(&contig);

        // SPDI position 13 = 0-based 13 = inserts between 1-based 13 and 14.
        let spdi = SpdiVariant::insertion("NC_000001.11", 13, "ATCGATCGATCG");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        // Expect ins, not dup. Confirm the rendered string contains "ins"
        // and not "dup".
        let s = hgvs.to_string();
        assert!(s.contains("ins"), "expected ins-form, got {}", s);
        assert!(!s.contains("dup"), "expected not dup, got {}", s);
    }

    #[test]
    fn audit_pin_no_ref_spdi_to_hgvs_renders_dup_shape_as_ins() {
        // Pins issue #119 documented behavior: without a reference,
        // spdi_to_hgvs cannot prove tandem dup, so the dup-shaped SPDI
        // 102::ATG (which round-tripped from g.100_102dupATG under the
        // post-#390 interbase-correct convention) is rendered as
        // g.102_103insATG. If a future change attempts to "fix" the
        // round-trip without a reference, this audit pin will fail and
        // demand explicit reconsideration.
        let spdi = SpdiVariant::insertion("NC_000001.11", 102, "ATG");
        let hgvs = spdi_to_hgvs(&spdi).unwrap();
        assert_eq!(hgvs.to_string(), "NC_000001.11:g.102_103insATG");
    }

    #[test]
    fn dup_recovery_is_idempotent_through_two_roundtrips() {
        let mut contig = "N".repeat(99);
        contig.push_str("ATG");
        contig.push_str(&"N".repeat(20));
        let provider = provider_with_genomic(&contig);

        let original = "NC_000001.11:g.100_102dupATG";
        let hgvs1 = parse_hgvs(original).unwrap();
        let spdi1 = hgvs_to_spdi_simple(&hgvs1).unwrap();
        let hgvs2 = spdi_to_hgvs_with_ref(&spdi1, &provider).unwrap();
        let spdi2 = hgvs_to_spdi_simple(&hgvs2).unwrap();
        let hgvs3 = spdi_to_hgvs_with_ref(&spdi2, &provider).unwrap();

        assert_eq!(spdi1, spdi2);
        assert_eq!(hgvs2.to_string(), hgvs3.to_string());
        assert_eq!(hgvs3.to_string(), original);
    }

    #[test]
    fn spdi_to_hgvs_with_ref_recovers_dup_for_mito_accession() {
        // Mock contig for NC_012920.1 with 1-based bases 100..102 = "ATG".
        let mut contig = "N".repeat(99);
        contig.push_str("ATG");
        contig.push_str(&"N".repeat(20));

        let mut provider = crate::reference::mock::MockProvider::new();
        provider.add_genomic_sequence("NC_012920.1", &contig);

        // SPDI 102 (interbase, #390) sits AFTER 1-based 102; the
        // 5' flank "ATG" matches the inserted "ATG" so dup recovers.
        let spdi = SpdiVariant::insertion("NC_012920.1", 102, "ATG");
        let hgvs = spdi_to_hgvs_with_ref(&spdi, &provider).unwrap();
        // After #270, SPDI→HGVS preserves the m. coord system for known
        // mitochondrial accessions (NC_012920.*); dup recovery applies
        // uniformly to genomic and mitochondrial variants.
        assert_eq!(hgvs.to_string(), "NC_012920.1:m.100_102dupATG");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_mt_dup_with_seq() {
        let hgvs = parse_hgvs("NC_012920.1:m.100_102dupATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI interbase 102 (#390): boundary AFTER 1-based 102.
        assert_eq!(spdi.position, 102);
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_mt_identity() {
        let hgvs = parse_hgvs("NC_012920.1:m.3243A=").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 3242);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "A");
    }

    // ----- n. (non-coding transcript) ----------------------------------------

    #[test]
    fn test_hgvs_to_spdi_simple_tx_substitution() {
        // n. — SPDI emitted on the transcript accession.
        let hgvs = parse_hgvs("NR_046018.2:n.5C>G").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.sequence, "NR_046018.2");
        assert_eq!(spdi.position, 4); // 5 (1-based) → 4 (0-based)
        assert_eq!(spdi.deletion, "C");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_insertion() {
        let hgvs = parse_hgvs("NR_046018.2:n.10_11insATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.sequence, "NR_046018.2");
        // SPDI interbase 10 (#390): boundary AFTER 1-based 10.
        assert_eq!(spdi.position, 10);
        assert_eq!(spdi.insertion, "ATG");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_deletion_with_seq() {
        let hgvs = parse_hgvs("NR_046018.2:n.10_12delATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_identity() {
        let hgvs = parse_hgvs("NR_046018.2:n.10A=").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "A");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_intronic_is_unrepresentable() {
        // n.100+5: an intronic offset cannot be expressed as a positional SPDI.
        //
        // The simple path used to call this `MissingReferenceData` and say the
        // position "requires reference provider with exon data", which named a
        // remedy that does not exist — the provider-backed path refuses an
        // intronic position too (`resolve_tx_pos`). It is a limit of SPDI, so
        // it declines as `UnrepresentableInSpdi` on both paths.
        let hgvs = parse_hgvs("NR_046018.2:n.100+5A>G").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "expected a representation limit, got {result:?}"
        );
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("intronic"), "msg: {}", msg);
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_downstream_needs_provider() {
        // n.*5: downstream of transcript end; needs transcript length.
        // Constructed rather than parsed — see `tx_downstream_sub` (#1748).
        let hgvs = tx_downstream_sub("NR_046018.2", 5);
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    #[test]
    fn test_hgvs_to_spdi_simple_tx_negative_base_needs_provider() {
        // n.-3: upstream of transcript start; the simple path has no way to
        // anchor it without knowing the transcript length.
        let hgvs = parse_hgvs("NR_046018.2:n.-3A>G").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    // ----- r. (RNA) ----------------------------------------------------------

    #[test]
    fn test_hgvs_to_spdi_simple_dna_lowercase_uppercased() {
        // Lowercase DNA bases (e.g. `g.100a>g`) must emit uppercase SPDI
        // alleles per the doc on `apply_alphabet`. Regression test: the DNA
        // branch previously preserved input case.
        let hgvs = parse_hgvs("NC_000001.11:g.100a>g").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_rna_substitution_lowercase() {
        // r.5c>g (lowercase RNA) → SPDI uses uppercase DNA alphabet.
        let hgvs = parse_hgvs("NR_046018.2:r.5c>g").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.sequence, "NR_046018.2");
        assert_eq!(spdi.position, 4);
        assert_eq!(spdi.deletion, "C");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_rna_substitution_u_to_t() {
        // r.5u>g: U on the deleted side rewrites to T for SPDI.
        let hgvs = parse_hgvs("NR_046018.2:r.5u>g").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.deletion, "T");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_rna_insertion_u_to_t() {
        // r.10_11insauug → SPDI insertion ATTG (a→A, u→T, u→T, g→G).
        let hgvs = parse_hgvs("NR_046018.2:r.10_11insauug").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        // SPDI interbase 10 (#390): boundary AFTER 1-based 10.
        assert_eq!(spdi.position, 10);
        assert_eq!(spdi.deletion, "");
        assert_eq!(spdi.insertion, "ATTG");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_rna_deletion_with_seq() {
        let hgvs = parse_hgvs("NR_046018.2:r.10_12delauu").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "ATT"); // a→A, u→T, u→T
    }

    #[test]
    fn test_hgvs_to_spdi_simple_rna_intronic_is_unrepresentable() {
        // As on the `n.` axis above: a representation limit, not a provider gap.
        let hgvs = parse_hgvs("NR_046018.2:r.10+5a>g").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "expected a representation limit, got {result:?}"
        );
    }

    // ----- p. (protein) — rejected with helpful error -----------------------

    #[test]
    fn test_hgvs_to_spdi_simple_protein_rejected() {
        let hgvs = parse_hgvs("NP_000079.2:p.Arg600Gln").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::UnsupportedVariantType { .. })
        ));
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("protein") && msg.contains("SPDI"),
            "expected helpful protein-rejection message; got: {}",
            msg
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_protein_rejected() {
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NP_000079.2:p.Arg600Gln").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(matches!(
            result,
            Err(ConversionError::UnsupportedVariantType { .. })
        ));
    }

    // ----- c. (CDS) — provider-aware ----------------------------------------

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_substitution() {
        let provider = make_test_provider();
        // c.1A>G: cds_start=6, so c.1 → tx 6 → SPDI 5
        let hgvs = parse_hgvs("NM_TEST.1:c.1A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NM_TEST.1");
        assert_eq!(spdi.position, 5);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_insertion() {
        let provider = make_test_provider();
        // c.1_2insATG: cds_start=6 → tx start_one_based 6 → SPDI
        // interbase position 6 (boundary AFTER 1-based 6; #390).
        let hgvs = parse_hgvs("NM_TEST.1:c.1_2insATG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 6);
        assert_eq!(spdi.insertion, "ATG");
    }

    // ----- position-range insert payloads are read on the DESCRIPTION'S axis --
    //
    // A payload span is spelled in the enclosing description's own coordinate
    // system, so on `c.` (and on a coding `r.`) it needs the same
    // `cds_start + N - 1` shift the *location* gets — and on `n.` it needs no
    // shift at all. Reading it unshifted is a silent wrong-bases answer that no
    // genomic test can see, because on `g.` the two frames coincide.
    //
    // `make_test_provider`'s `NM_TEST.1` has `cds_start = 6`, and tx 3..=5 reads
    // `AAA` while tx 8..=10 (== `c.3_5`) reads `CCC`. Every assertion below is
    // chosen so the shifted and unshifted answers differ.

    #[test]
    fn a_cds_axis_range_insert_reads_its_payload_on_the_cds_axis() {
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:c.1_2ins3_5").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        // c.1_2 -> tx 6_7 -> SPDI interbase 6 (boundary AFTER 1-based 6; #390).
        assert_eq!(spdi.position, 6);
        assert_eq!(
            spdi.insertion, "CCC",
            "c.3_5 is tx 8..=10; reading tx 3..=5 unshifted would give AAA"
        );
    }

    #[test]
    fn a_cds_axis_range_delins_reads_its_payload_on_the_cds_axis() {
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:c.1_3delins3_5").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        // c.1_3 -> tx 6_8 -> SPDI 5; the deleted bases are tx 6..=8 == TGC.
        assert_eq!(spdi.position, 5);
        assert_eq!(spdi.deletion, "TGC");
        assert_eq!(
            spdi.insertion, "CCC",
            "the delins arm resolves its payload on the same axis as the ins arm"
        );
    }

    #[test]
    fn a_coding_rna_axis_range_insert_reads_its_payload_cds_relative() {
        let provider = make_test_provider();
        // On a coding transcript `r.N` denotes the same base as `c.N`, which
        // `resolve_rna_pos` already honours for the location. The payload must
        // agree, or one description is read in two frames.
        let hgvs = parse_hgvs("NM_TEST.1:r.1_2ins3_5").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 6);
        assert_eq!(spdi.insertion, "CCC");
    }

    #[test]
    fn a_cds_axis_compound_insert_reads_its_span_part_on_the_cds_axis() {
        let provider = make_test_provider();
        // A span *inside a bracket* resolves through the same leaf as a bare
        // one, so it must land in the same frame. `[T;3_5]` is the literal `T`
        // followed by `c.3_5` == tx 8..=10 == `CCC`.
        let hgvs = parse_hgvs("NM_TEST.1:c.1_2ins[T;3_5]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 6);
        assert_eq!(
            spdi.insertion, "TCCC",
            "a bracketed span part must be read on the same axis as a bare one; \
             unshifted it would give TAAA"
        );
    }

    #[test]
    fn a_noncoding_axis_range_insert_reads_its_payload_unshifted() {
        let provider = make_test_provider();
        // The negative control: `n.` positions ARE transcript offsets, so the
        // same payload spelling must read different bases from the `c.` case
        // above. Without this the fix could be a blanket shift and still pass.
        let hgvs = parse_hgvs("NM_TEST.1:n.1_2ins3_5").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 1);
        assert_eq!(
            spdi.insertion, "AAA",
            "n.3_5 is tx 3..=5; shifting it by cds_start would give CCC"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_deletion_with_seq() {
        let provider = make_test_provider();
        // c.1_3delATG: tx 6_8 → SPDI 5:ATG:
        let hgvs = parse_hgvs("NM_TEST.1:c.1_3delATG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 5);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_5utr() {
        let provider = make_test_provider();
        // c.-3A>G: 3 bases before cds_start (6) → tx 3 → SPDI 2
        let hgvs = parse_hgvs("NM_TEST.1:c.-3A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 2);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_3utr() {
        let provider = make_test_provider();
        // c.*2A>G: 2 bases past cds_end (35) → tx 37 → SPDI 36
        let hgvs = parse_hgvs("NM_TEST.1:c.*2A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 36);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_exonic_past_3prime_end_declines() {
        // NM_TEST.1 is 40 bases (cds 6-35). c.99999 -> tx 100004, off-sequence.
        // #971: must decline, not emit an off-sequence SPDI coordinate.
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:c.99999A>G").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic c.N must decline with InvalidPosition, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_exonic_range_past_3prime_end_declines() {
        // In a range, an over-length end must also decline (#971 acceptance: "in a range").
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:c.20_99999del").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic c. range must decline, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_exonic_last_base_ok() {
        // c.30 -> tx 35 (last CDS base, in bounds) must still resolve unchanged.
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:c.30A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 34, "c.30 -> tx 35 -> SPDI 34");
    }

    /// r.*N anchors at `cds_end`, not `sequence_length()` — closes
    /// #390 item 2. With the test fixture (cds_end=35, tx_len=40),
    /// r.*2 must resolve to tx position 37 (SPDI 36), matching the
    /// equivalent `c.*2` resolution.
    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_3utr_anchors_at_cds_end() {
        let provider = make_test_provider();
        // For SPDI emission r. lowercase is normalized to upper / U→T
        // by the conversion path; r.*2a>g exercises the 3'UTR anchor.
        let hgvs = parse_hgvs("NM_TEST.1:r.*2a>g").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(
            spdi.position, 36,
            "r.*2 must anchor at cds_end (35) + 2 → tx 37 → SPDI 36; pre-#390 \
             this anchored at sequence_length (40) + 2 → off-sequence SPDI 41"
        );
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_coding_matches_cds() {
        // On a CODING transcript r.N is CDS-relative (#469): r.N and c.N denote the
        // same base, so they must resolve to the same SPDI position. NM_TEST.1
        // cds_start=6, so r.1 == c.1 -> tx 6 -> SPDI 5; r.30 == c.30 -> tx 35 -> SPDI 34.
        let provider = make_test_provider();
        for (r_str, c_str) in [
            ("NM_TEST.1:r.1a>g", "NM_TEST.1:c.1A>G"),
            ("NM_TEST.1:r.30a>g", "NM_TEST.1:c.30A>G"),
        ] {
            let r = hgvs_to_spdi(&parse_hgvs(r_str).unwrap(), &provider).unwrap();
            let c = hgvs_to_spdi(&parse_hgvs(c_str).unwrap(), &provider).unwrap();
            assert_eq!(r.position, c.position, "{r_str} must match {c_str}");
        }
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_coding_first_base() {
        // Regression on the exact confirmed values: r.1a>g -> SPDI 5 (was 0).
        let provider = make_test_provider();
        let spdi = hgvs_to_spdi(&parse_hgvs("NM_TEST.1:r.1a>g").unwrap(), &provider).unwrap();
        assert_eq!(spdi.position, 5, "coding r.1 -> tx 6 (cds_start) -> SPDI 5");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_coding_past_3prime_end_declines() {
        // Now that coding r.N routes through cds_to_tx (#469/#971), an over-length
        // coding r.N must still decline rather than emit an off-sequence SPDI
        // position: cds_to_tx returns an out-of-range base, which
        // ensure_tx_in_bounds then rejects — same as over-length coding c.N.
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:r.99999a>g").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic coding r.N must decline with InvalidPosition, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_coding_range_matches_cds() {
        // The coding r.N == c.N CDS-relative identity must hold across BOTH
        // endpoints of a range, not just single bases: r.1_30del and c.1_30del
        // must produce the same SPDI (position and deleted span).
        let provider = make_test_provider();
        let r = hgvs_to_spdi(&parse_hgvs("NM_TEST.1:r.1_30del").unwrap(), &provider).unwrap();
        let c = hgvs_to_spdi(&parse_hgvs("NM_TEST.1:c.1_30del").unwrap(), &provider).unwrap();
        assert_eq!(
            r.position, c.position,
            "r.1_30del must match c.1_30del position"
        );
        assert_eq!(
            r.deletion.len(),
            c.deletion.len(),
            "r.1_30del must delete the same span as c.1_30del"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_coding_missing_cds_end_declines() {
        // A coding transcript (cds_start set) with NO cds_end is malformed. A
        // coding r.N cannot be resolved CDS-relative without a CDS end, so it
        // must DECLINE — not silently fall back to an unbounded,
        // transcript-absolute r.N (off by cds_start-1). The decline surfaces as
        // InvalidPosition, which propagates past the resolve_rna_exonic_bounded
        // MissingReferenceData fallback.
        let tx = Transcript::new(
            "NM_NOCDSEND.1".to_string(),
            Some("TEST".to_string()),
            Strand::Plus,
            "AAAAATGCCCAAAGGGTTTAGGCCCAAAGGGTTATAAA".to_string() + "AA",
            Some(6),
            None,
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        let result = hgvs_to_spdi(&parse_hgvs("NM_NOCDSEND.1:r.5a>g").unwrap(), &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "coding r.N on a transcript missing cds_end must decline with \
             InvalidPosition, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_cds_intronic_rejected() {
        // Intronic c. cannot be expressed as a positional SPDI: SPDI has no
        // offset notation. The provider-aware path surfaces a clear error —
        // and it is a *representation* error, not a reference one: this
        // provider serves the transcript, and the decline is raised before it
        // is asked anything.
        let provider = make_intronic_provider();
        let hgvs = parse_hgvs("NM_INTRON.1:c.10+5A>G").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::UnrepresentableInSpdi { .. })),
            "expected a representation limit, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_unknown_transcript() {
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NM_TEST.1:c.1A>G").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("transcript") || msg.contains("NM_TEST"));
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_falls_through_to_simple_for_genome() {
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.12345A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.to_string(), "NC_000001.11:12344:A:G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_falls_through_to_simple_for_mt() {
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NC_012920.1:m.3243A>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.to_string(), "NC_012920.1:3242:A:G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_falls_through_to_simple_for_exonic_n() {
        // Exonic positive-base n. doesn't actually need provider data; the
        // provider-aware path delegates to the simple path.
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NR_046018.2:n.5C>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.to_string(), "NR_046018.2:4:C:G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_tx_exonic_past_3prime_end_declines() {
        // n. treats the base as a direct transcript position; NM_TEST.1 is 40 bases.
        // n.99999 is off-sequence and must decline (#971).
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:n.99999C>G").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic n.N must decline with InvalidPosition, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_tx_exonic_range_past_3prime_end_declines() {
        // Over-length end in an n. range must also decline (#971 acceptance: "in a range").
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:n.10_99999del").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic n. range must decline, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_tx_exonic_last_base_ok() {
        // n.40 -> tx 40 (last base, in bounds) still resolves.
        let provider = make_test_provider();
        let hgvs = parse_hgvs("NM_TEST.1:n.40C>G").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 39, "n.40 -> tx 40 -> SPDI 39");
    }

    /// Single-exon non-coding transcript: 40 bases, no CDS. Exonic r.N maps the
    /// base directly to the transcript position (NR_ has no CDS anchor), so it is
    /// the clean fixture for r.N 3'-bound tests (avoids the coding-r.N #469 case).
    fn make_noncoding_provider() -> MockProvider {
        let tx = Transcript::new(
            "NR_TEST.1".to_string(),
            Some("NCTEST".to_string()),
            Strand::Plus,
            "A".repeat(40),
            None,
            None,
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        provider
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_past_3prime_end_declines() {
        let provider = make_noncoding_provider();
        let hgvs = parse_hgvs("NR_TEST.1:r.99999a>g").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic r.N must decline with InvalidPosition, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_range_past_3prime_end_declines() {
        let provider = make_noncoding_provider();
        let hgvs = parse_hgvs("NR_TEST.1:r.10_99999del").unwrap();
        let result = hgvs_to_spdi(&hgvs, &provider);
        assert!(
            matches!(result, Err(ConversionError::InvalidPosition { .. })),
            "over-length exonic r. range must decline, got {result:?}"
        );
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_rna_exonic_last_base_ok() {
        // r.40 -> tx 40 (last base, in bounds) still resolves.
        let provider = make_noncoding_provider();
        let hgvs = parse_hgvs("NR_TEST.1:r.40a>g").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 39, "r.40 -> tx 40 -> SPDI 39");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_falls_through_to_simple_for_exonic_r() {
        // Best-effort (#971): provider lacks the transcript, so the exonic r.
        // conversion falls back to the unbounded simple-path value rather than
        // erroring — mirrors the n. sibling test.
        let provider = MockProvider::new();
        let hgvs = parse_hgvs("NR_046018.2:r.5c>g").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.to_string(), "NR_046018.2:4:C:G");
    }

    #[test]
    fn test_hgvs_to_spdi_with_provider_n_downstream_rejected() {
        // n. has no CDS anchor, so `n.*N` is past the transcript end and
        // cannot be expressed in SPDI on the transcript accession. The
        // provider-aware path must reject rather than silently emit an
        // off-sequence position at `tx_len + N`.
        let tx = Transcript::new(
            "NR_NONCODING.1".to_string(),
            Some("NONCODING".to_string()),
            Strand::Plus,
            "A".repeat(40),
            None,
            None,
            vec![Exon::new(1, 1, 40)],
            None,
            None,
            None,
            GenomeBuild::default(),
            ManeStatus::default(),
            None,
            None,
        );
        let mut provider = MockProvider::new();
        provider.add_transcript(tx);
        // Constructed rather than parsed — see `tx_downstream_sub` (#1748).
        let hgvs = tx_downstream_sub("NR_NONCODING.1", 5);
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::InvalidPosition { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("downstream n.") && msg.contains("genomic projection"),
            "expected downstream-n rejection, got: {}",
            msg
        );
    }

    // ----- Edit-type passthrough on new coord systems -----------------------

    #[test]
    fn test_hgvs_to_spdi_simple_n_short_form_inversion_requires_provider() {
        // Short-form `n.` inversion needs the provider to fetch reference
        // bases — same shape as `g.`.
        let hgvs = parse_hgvs("NR_046018.2:n.10_20inv").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    #[test]
    fn test_hgvs_to_spdi_simple_m_short_form_inversion_requires_provider() {
        // Short-form `m.` inversion needs the provider to fetch reference
        // bases — same shape as `g.`.
        let hgvs = parse_hgvs("NC_012920.1:m.100_200inv").unwrap();
        let result = hgvs_to_spdi_simple(&hgvs);
        assert!(matches!(
            result,
            Err(ConversionError::MissingReferenceData { .. })
        ));
    }

    // ---------------------------------------------------------------------
    // Inversion: provider-aware emission (#118)
    // ---------------------------------------------------------------------

    #[test]
    fn test_hgvs_to_spdi_inversion_short_form_with_provider() {
        // 1-based 100..102 is "ATG" → revcomp "CAT"
        let provider = make_test_genomic_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NC_000001.11");
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_explicit_sequence_no_provider() {
        // Explicit sequence bypasses the provider entirely — matches the
        // explicit-form policy already used for del/dup.
        let hgvs = parse_hgvs("NC_000001.11:g.100_102invATG").unwrap();
        let spdi = hgvs_to_spdi_simple(&hgvs).unwrap();
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_explicit_sequence_does_not_consult_provider() {
        // Same as above but routed through the provider-aware path with an
        // empty provider — explicit-form must not call the provider.
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102invATG").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_single_base() {
        // Inversion of a single base 'A' → 'T'. `g.100_100inv` cannot be
        // parsed — DNA/inversion.md:16 forbids a one-nucleotide inversion —
        // so the variant is built directly to keep the conversion arm
        // covered for callers that construct an AST themselves.
        let provider = make_test_genomic_provider();
        let hgvs = HgvsVariant::Genome(GenomeVariant {
            accession: parse_accession("NC_000001.11").unwrap().1,
            gene_symbol: None,
            loc_edit: LocEdit::new(
                crate::hgvs::interval::GenomeInterval::point(GenomePos::new(100)),
                NaEdit::Inversion {
                    sequence: None,
                    length: None,
                },
            ),
        });
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "A");
        assert_eq!(spdi.insertion, "T");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_palindrome_round_trip() {
        // ATAT is its own reverse complement; del == ins.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(99);
        contig.push_str("ATAT");
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NC_000001.11", &contig);
        let hgvs = parse_hgvs("NC_000001.11:g.100_103inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATAT");
        assert_eq!(spdi.insertion, "ATAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_short_form_missing_provider_data() {
        // Provider has no contig; expect a MissingReferenceData with the
        // accession + 1-based interval in the message (same shape as #117).
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_102inv").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
        let msg = err.to_string();
        assert!(msg.contains("NC_000001.11"));
        assert!(msg.contains("100"));
        assert!(msg.contains("102"));
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_m_short_form_with_provider() {
        // `m.` works the same as `g.` — accession is the mito contig.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(99);
        contig.push_str("ATG");
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NC_012920.1", &contig);
        let hgvs = parse_hgvs("NC_012920.1:m.100_102inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NC_012920.1");
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_n_short_form_with_provider() {
        // `n.` (non-coding tx): SPDI emits on the transcript accession.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(9);
        contig.push_str("ATGCATGC"); // 1-based 10..17
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NR_046018.2", &contig);
        let hgvs = parse_hgvs("NR_046018.2:n.10_12inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NR_046018.2");
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
    }

    #[test]
    fn test_hgvs_to_spdi_inversion_r_short_form_dna_alphabet() {
        // `r.` input — SPDI must come out in DNA alphabet (T, not U).
        // Reference bases on transcripts are stored as DNA, so the
        // del/ins emitted here are uppercase DNA.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(9);
        contig.push_str("ATGCATGC");
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NR_046018.2", &contig);
        let hgvs = parse_hgvs("NR_046018.2:r.10_12inv").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATG");
        assert_eq!(spdi.insertion, "CAT");
        // The output must be DNA (no U).
        assert!(!spdi.deletion.contains('U'));
        assert!(!spdi.insertion.contains('U'));
    }

    // ---------------------------------------------------------------------
    // Repeat: provider-aware emission (#118)
    // ---------------------------------------------------------------------

    /// Build a provider with an AT-tandem repeat tract:
    ///   1-based 100..105 = "ATATAT" (3 copies of AT)
    ///   1-based 200..209 = "ATATATATAT" (5 copies of AT)
    fn make_repeat_provider() -> crate::reference::mock::MockProvider {
        let mut p = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(99);
        contig.push_str("ATATAT"); // 1-based 100..105 (6 bases)
        contig.push_str(&"N".repeat(94)); // pad through 1-based 199
        contig.push_str("ATATATATAT"); // 1-based 200..209 (10 bases)
        contig.push_str(&"N".repeat(50));
        p.add_genomic_sequence("NC_000001.11", &contig);
        p
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_expansion_with_provider() {
        // Reference has 3 copies of AT (100..105 = ATATAT); allele has 5.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[5]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NC_000001.11");
        assert_eq!(spdi.position, 99);
        assert_eq!(spdi.deletion, "ATATAT"); // 3 copies in reference
        assert_eq!(spdi.insertion, "ATATATATAT"); // 5 copies on allele
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_contraction_with_provider() {
        // Reference has 5 copies (200..209); allele has 3.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.200_209AT[3]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.position, 199);
        assert_eq!(spdi.deletion, "ATATATATAT"); // 5 copies
        assert_eq!(spdi.insertion, "ATATAT"); // 3 copies
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_no_change_with_provider() {
        // Reference and allele both have 3 copies → del == ins (a valid
        // SPDI identity-shape delins).
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[3]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.deletion, "ATATAT");
        assert_eq!(spdi.insertion, "ATATAT");
    }

    #[test]
    fn test_hgvs_to_spdi_simple_repeat_requires_provider() {
        // No provider → MissingReferenceData (replaces prior
        // UnsupportedEditType behaviour).
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[5]").unwrap();
        let err = hgvs_to_spdi_simple(&hgvs).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_missing_provider_data() {
        let provider = crate::reference::mock::MockProvider::new();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[5]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
        let msg = err.to_string();
        assert!(msg.contains("NC_000001.11"));
        assert!(msg.contains("100"));
        assert!(msg.contains("105"));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_uncertain_count_unsupported() {
        // RepeatCount::Range — uncertain — cannot be a single SPDI value.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[3_5]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::UnsupportedEditType { .. }));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_unknown_count_unsupported() {
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[?]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::UnsupportedEditType { .. }));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_genotype_unsupported() {
        // Genotype-style additional counts cannot be a single SPDI.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[3][5]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::UnsupportedEditType { .. }));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_no_unit_unsupported() {
        // `g.100_105(5)` parenthesized form: NaEdit::Repeat with no unit.
        // Without a unit we cannot construct the inserted sequence.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_105(5)").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::MissingReferenceData { .. }));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_span_not_multiple_of_unit() {
        // Span 100..104 is 5 bases; AT unit is 2 bases → not divisible.
        let provider = make_repeat_provider();
        let hgvs = parse_hgvs("NC_000001.11:g.100_104AT[5]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::InvalidPosition { .. }));
        let msg = err.to_string();
        assert!(msg.contains("not a multiple"));
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_span_does_not_match_unit() {
        // Reference span is `ATGCAT` (6 bases, multiple of unit length 2)
        // but the locus is NOT an AT tandem repeat. Must reject rather
        // than silently emit a wrong SPDI delins.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(99);
        contig.push_str("ATGCAT"); // 1-based 100..105 — not a tandem AT[3]
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NC_000001.11", &contig);

        let hgvs = parse_hgvs("NC_000001.11:g.100_105AT[5]").unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::InvalidPosition { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("does not match repeat unit"),
            "expected mismatch message, got: {}",
            msg
        );
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_n_with_provider() {
        // `n.` repeat — SPDI on transcript accession.
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(9);
        contig.push_str("ATATAT"); // 1-based 10..15
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NR_046018.2", &contig);
        let hgvs = parse_hgvs("NR_046018.2:n.10_15AT[5]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NR_046018.2");
        assert_eq!(spdi.position, 9);
        assert_eq!(spdi.deletion, "ATATAT");
        assert_eq!(spdi.insertion, "ATATATATAT");
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_expansion_too_large() {
        // A huge user-supplied count must be refused before allocating the
        // expanded ins-string. The reference span itself is small (and a
        // valid AT tandem) so this isolates the size guard.
        let provider = make_repeat_provider();
        let huge = MAX_REPEAT_EXPANSION_BASES / 2 + 1; // unit.len() == 2
        let hgvs = parse_hgvs(&format!("NC_000001.11:g.100_105AT[{}]", huge)).unwrap();
        let err = hgvs_to_spdi(&hgvs, &provider).unwrap_err();
        assert!(matches!(err, ConversionError::UnsupportedEditType { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("exceeds SPDI ins-string cap"),
            "expected size-cap message, got: {}",
            msg
        );
    }

    #[test]
    fn test_hgvs_to_spdi_repeat_m_with_provider() {
        let mut provider = crate::reference::mock::MockProvider::new();
        let mut contig = "N".repeat(99);
        contig.push_str("ATATAT"); // 1-based 100..105
        contig.push_str(&"N".repeat(50));
        provider.add_genomic_sequence("NC_012920.1", &contig);
        let hgvs = parse_hgvs("NC_012920.1:m.100_105AT[5]").unwrap();
        let spdi = hgvs_to_spdi(&hgvs, &provider).unwrap();
        assert_eq!(spdi.sequence, "NC_012920.1");
        assert_eq!(spdi.deletion, "ATATAT");
        assert_eq!(spdi.insertion, "ATATATATAT");
    }

    // ------------------------------------------------------------------
    // Genomic offsets (#1628)
    // ------------------------------------------------------------------

    /// A `g.` position carrying a `+`/`-` offset must not be silently
    /// flattened onto its base. `checklist.md:16` prohibits an offset on a
    /// genomic position and SPDI has no offset notation, so the only two
    /// honest answers are "refuse" and "resolve"; there is nothing to
    /// resolve against on a bare genomic accession, so the answer is refuse.
    ///
    /// Dropping the offset is the third, dishonest answer: it makes
    /// `g.266+2del`, `g.266-268del` and `g.266del` — which `normalize`
    /// treats as three different variants — collapse onto one triple.
    ///
    /// All three genomic axes are exercised, on both public entry points, so
    /// each of the six guard call sites is covered: `m.` and `o.` hold the
    /// same `Interval<GenomePos>` as `g.` and are equally able to carry an
    /// offset the parser accepts. The verdict is asserted rather than a bare
    /// `is_err()` — the contract is *refused as an invalid position, naming
    /// the offset*, and "failed somehow" would also be satisfied by an
    /// unrelated error on a path where the guard had been removed. The
    /// message's coordinate prefix is asserted too, since the axis label is
    /// passed in per call site and a copy-paste is otherwise invisible.
    #[test]
    fn a_genomic_offset_is_refused_rather_than_dropped() {
        let provider = identity_provider();
        for (descriptor, coord) in [
            ("NC_000001.11:g.10+2delC", "g"),
            ("NC_000001.11:g.10-2delC", "g"),
            ("NC_000001.11:g.10+2_12delCGT", "g"),
            ("NC_000001.11:g.10_12+2delCGT", "g"),
            ("NC_012920.1:m.10+2delC", "m"),
            ("NC_012920.1:m.10_12+2delCGT", "m"),
            ("NC_001416.1:o.10+2delC", "o"),
            ("NC_001416.1:o.10_12+2delCGT", "o"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let err = match converted {
                    Err(err) => err,
                    Ok(spdi) => {
                        panic!(
                            "`{descriptor}` converted {path} to `{spdi}`; the offset was dropped"
                        )
                    }
                };
                assert!(
                    matches!(err, ConversionError::InvalidPosition { .. }),
                    "`{descriptor}` {path} must be refused as InvalidPosition, got {err:?}"
                );
                let message = err.to_string();
                assert!(
                    message.contains("carries a +/- offset"),
                    "`{descriptor}` {path} was refused for some other reason: {message}"
                );
                assert!(
                    message.contains(&format!("{coord}. position")),
                    "`{descriptor}` {path} named the wrong coordinate axis: {message}"
                );
            }
        }
    }

    /// The transcript axes are where a `+`/`-` offset is legitimate HGVS, and
    /// the genomic guard must not reach them. Each still declines for its own
    /// reason — `UnrepresentableInSpdi`, "cannot be expressed in SPDI without
    /// genomic projection" — which is a different verdict from the genomic
    /// `InvalidPosition`, and the difference is the point: `c.10+5` is a
    /// well-formed position SPDI cannot carry, `g.10+2` is not a well-formed
    /// position at all.
    ///
    /// The carrier used to be `MissingReferenceData`, which named the wrong
    /// obstacle: the provider is serving this transcript — the exonic siblings
    /// below prove it — and the `c.` arm declines before the provider is
    /// consulted at all. Consumers classify a conversion failure on this
    /// variant, and a downstream one read the mislabel as "could not tell"; see
    /// `equivalence::checker`'s `TripleDecline::from_conversion_error`.
    ///
    /// Their exonic siblings on the same providers still convert, so this pins
    /// that the axes are working rather than merely erroring.
    #[test]
    fn a_transcript_axis_offset_declines_for_its_own_reason() {
        let provider = make_intronic_provider();
        for (descriptor, exonic_sibling) in [
            ("NM_INTRON.1:c.10+5A>G", "NM_INTRON.1:c.10A>G"),
            ("NM_INTRON.1:n.10+5A>G", "NM_INTRON.1:n.10A>G"),
            ("NM_INTRON.1:r.10+5a>g", "NM_INTRON.1:r.10a>g"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            let err = hgvs_to_spdi(&variant, &provider)
                .expect_err("an intronic transcript position has no SPDI representation");
            assert!(
                matches!(err, ConversionError::UnrepresentableInSpdi { .. }),
                "`{descriptor}` must decline as UnrepresentableInSpdi — the reference is served \
                 and is not the obstacle, got {err:?}"
            );
            assert!(
                err.to_string().contains("genomic projection"),
                "`{descriptor}` lost its own reason: {err}"
            );
            let exonic = parse_hgvs(exonic_sibling).expect("fixture must parse");
            assert!(
                hgvs_to_spdi(&exonic, &provider).is_ok(),
                "`{exonic_sibling}` must still convert — the axis is not broken, \
                 only its intronic positions are unrepresentable"
            );
        }
    }

    // ------------------------------------------------------------------
    // Genomic special positions (#1643)
    // ------------------------------------------------------------------

    /// `pter`, `qter` and `cen` name no numeric coordinate, and `GenomePos`
    /// stores `base: 0` for all three. `hgvs_to_spdi` read `base` and never
    /// looked at `special`, so every special position resolved to base 0 — the
    /// sibling of the dropped `offset` of #1628, in the same helper and with
    /// the same consequence: descriptions of different variants collapse onto
    /// one triple.
    ///
    /// **Every descriptor here spells its own bases, and that is the whole
    /// reason the class survived #1641.** A description carrying its bases
    /// needs no provider fetch and no position resolution, so none of the
    /// checks that appear to cover this ever runs. The shapes that do not spell
    /// their bases were refused *incidentally* and for the wrong reason —
    /// `g.pter_10del` by the 1-based check ("position 0 is not valid in HGVS"),
    /// `g.10_qterdel` by the fetch (`invalid 1-based interval [10, 0]`), the
    /// `m.`/`o.` forms by the circular-wraparound check reporting a wraparound
    /// that is not there — which is exactly why reading those refusals as
    /// coverage was wrong.
    ///
    /// The verdict is `InvalidPosition` for the reason #1641 established for
    /// the offset case: a special position cannot be *resolved* on a bare
    /// genomic accession — `pter` and `qter` are landmarks of the assembled
    /// chromosome, and `cen` of its centromere annotation, neither of which a
    /// sequence accession carries — so refusing is the only honest answer, and
    /// it differs from the transcript axes' `MissingReferenceData` because
    /// those decline a *well-formed* position SPDI cannot carry.
    ///
    /// Both entry points and every genomic axis, so all six guard call sites
    /// are covered, and the message is asserted rather than a bare `is_err()`:
    /// "failed somehow" is what every one of those incidental refusals already
    /// satisfied.
    #[test]
    fn a_genomic_special_position_is_refused_rather_than_flattened() {
        let provider = identity_provider();
        for (descriptor, coord) in [
            ("NC_000001.11:g.10_qterdelACGTACGTAC", "g"),
            ("NC_000001.11:g.10_cendelACGTACGTAC", "g"),
            ("NC_000001.11:g.10_qterdupACGTACGTAC", "g"),
            ("NC_000001.11:g.10_qterinvACGTACGTAC", "g"),
            ("NC_000001.11:g.pter_10delACGTACGTAC", "g"),
            ("NC_012920.1:m.10_qterdelACGTACGTAC", "m"),
            ("NC_012920.1:m.pter_10delACGTACGTAC", "m"),
            ("NC_001416.1:o.10_qterdelACGTACGTAC", "o"),
            ("NC_001416.1:o.pter_10delACGTACGTAC", "o"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let err = match converted {
                    Err(err) => err,
                    Ok(spdi) => panic!(
                        "`{descriptor}` converted {path} to `{spdi}`; the special position \
                         was flattened onto base 0"
                    ),
                };
                assert!(
                    matches!(err, ConversionError::InvalidPosition { .. }),
                    "`{descriptor}` {path} must be refused as InvalidPosition, got {err:?}"
                );
                let message = err.to_string();
                assert!(
                    message.contains("names no numeric coordinate"),
                    "`{descriptor}` {path} was refused for some other reason: {message}"
                );
                assert!(
                    message.contains(&format!("{coord}. position")),
                    "`{descriptor}` {path} named the wrong coordinate axis: {message}"
                );
            }
        }
    }

    /// The confluence failure the flattening produced, measured on `main`
    /// before the guard: a deletion running to the q-arm telomere, one running
    /// to the centromere, and a literal ten-base deletion all converted to
    /// `NC_000001.11:9:ACGTACGTAC:`. Three descriptions of three different
    /// things, one triple.
    ///
    /// Stated as the invariant rather than as three pinned errors, so it keeps
    /// meaning something if a future change makes any of these resolvable: what
    /// must never happen is two of them sharing an answer.
    ///
    /// **The denominator is asserted, because with the guard in place the
    /// `panic!` above is unreachable.** Two of the three descriptors are now
    /// refused and skipped by the `if let Ok`, so `seen` holds one triple and
    /// there is no pair left to collide — exactly the `0 of 0` shape this
    /// repository asserts denominators against. The census below is therefore
    /// what carries the meaning today, and it is written to fail the moment a
    /// special position becomes convertible again: that is precisely when the
    /// collision check goes live and has to be re-read rather than trusted.
    #[test]
    fn special_positions_do_not_collapse_onto_one_another() {
        /// Refused by the #1643 guard today, so they never reach `seen`.
        const CONVERTIBLE_TODAY: usize = 1;

        let provider = identity_provider();
        let descriptors = [
            "NC_000001.11:g.10_qterdelACGTACGTAC",
            "NC_000001.11:g.10_cendelACGTACGTAC",
            "NC_000001.11:g.10_19delACGTACGTAC",
        ];
        let mut seen: Vec<(String, String)> = Vec::new();
        for descriptor in descriptors {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            if let Ok(spdi) = hgvs_to_spdi(&variant, &provider) {
                let triple = spdi.to_string();
                if let Some((other, _)) = seen.iter().find(|(_, t)| *t == triple) {
                    panic!(
                        "`{descriptor}` and `{other}` are different variants but share the \
                         triple `{triple}`"
                    );
                }
                seen.push((descriptor.to_string(), triple));
            }
        }

        assert_eq!(
            seen.len(),
            CONVERTIBLE_TODAY,
            "{} of {} descriptors converted, expected {CONVERTIBLE_TODAY}: {seen:?}. \
             If this grew, a special position is convertible again and the collision check \
             above has just become live — read what it now compares before re-pinning this \
             number. If it shrank, the loop is comparing nothing at all",
            seen.len(),
            descriptors.len()
        );
        assert!(
            seen.len() < descriptors.len(),
            "every descriptor converted, so the #1643 guard is refusing nothing"
        );
    }

    /// The invariant the drop breaks, stated directly: two descriptions that
    /// `to_spdi` maps to the same triple must be the same variant. Here the
    /// offset-free sibling is the one legal spelling, so the offset-carrying
    /// ones must not share its triple.
    #[test]
    fn distinct_genomic_descriptions_do_not_share_one_triple() {
        let provider = identity_provider();
        let plain = hgvs_to_spdi(&parse_hgvs("NC_000001.11:g.10delC").unwrap(), &provider)
            .expect("the offset-free spelling is legal and must convert")
            .to_string();
        for descriptor in ["NC_000001.11:g.10+2delC", "NC_000001.11:g.10-2delC"] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            let got = hgvs_to_spdi(&variant, &provider).map(|s| s.to_string());
            assert_ne!(
                got.as_deref().ok(),
                Some(plain.as_str()),
                "`{descriptor}` and `NC_000001.11:g.10delC` are different variants \
                 to `normalize` but one triple to `to_spdi`"
            );
        }
    }

    // ------------------------------------------------------------------
    // Unresolvable transcript-axis end boundaries (#1804)
    // ------------------------------------------------------------------

    /// Assert one refusal carries #1804's verdict, reason and axis label.
    ///
    /// The verdict is checked rather than a bare `is_err()`: on these axes
    /// "failed somehow" is satisfied by the pre-existing `MissingReferenceData`
    /// declines for an intronic or downstream position, so a bare `is_err()`
    /// would pass on a path where this guard had been removed.
    fn assert_end_boundary_refused(
        descriptor: &str,
        coord: &str,
        path: &str,
        converted: Result<SpdiVariant, ConversionError>,
    ) {
        let err = match converted {
            Err(err) => err,
            Ok(spdi) => panic!(
                "`{descriptor}` converted {path} to `{spdi}`; the unresolvable end was \
                 collapsed onto the start"
            ),
        };
        assert!(
            matches!(err, ConversionError::InvalidPosition { .. }),
            "`{descriptor}` {path} must be refused as InvalidPosition — the same verdict this \
             axis already gives an unresolvable START — got {err:?}"
        );
        let message = err.to_string();
        assert!(
            message.contains("names no single coordinate"),
            "`{descriptor}` {path} was refused for some other reason: {message}"
        );
        assert!(
            message.contains(&format!("{coord}. interval end")),
            "`{descriptor}` {path} named the wrong coordinate axis: {message}"
        );
    }

    /// An end boundary that names no single coordinate — a range `(20_30)` or an
    /// unknown `?` — must be refused, not silently replaced by the start.
    ///
    /// Measured on `main` at `439617c2`: `c.10_(20_30)delAAAA` and
    /// `c.10_?delAAAA` both converted to `NM_INTRON.1:19:AAAA:`, and the
    /// short forms were worse — `c.10_(20_30)del` became `NM_INTRON.1:19:A:`,
    /// a one-base deletion standing in for a deletion of unknown extent.
    ///
    /// All three axes on both public entry points where each is reachable, so
    /// every one of the seven substitution sites is covered. `c.` has no
    /// no-provider path (`hgvs_to_spdi_simple` returns `ProviderRequired` for
    /// it), and `r.*5` is likewise provider-only, so those are listed
    /// separately rather than asserted through a path that declines earlier for
    /// an unrelated reason.
    #[test]
    fn an_unresolvable_transcript_end_is_refused_rather_than_collapsed() {
        let provider = make_intronic_provider();

        // Reachable on both entry points.
        for (descriptor, coord) in [
            ("NM_INTRON.1:n.10_(20_30)delAAAA", "n"),
            ("NM_INTRON.1:n.10_?delAAAA", "n"),
            ("NM_INTRON.1:r.10_(20_30)delaaaa", "r"),
            ("NM_INTRON.1:r.10_?delaaaa", "r"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            assert_end_boundary_refused(
                descriptor,
                coord,
                "without a provider",
                hgvs_to_spdi_simple(&variant),
            );
            assert_end_boundary_refused(
                descriptor,
                coord,
                "with a provider",
                hgvs_to_spdi(&variant, &provider),
            );
        }

        // Provider-only: `c.` needs the CDS start, and `r.*5` needs the
        // transcript length, so neither reaches the no-provider path.
        for (descriptor, coord) in [
            ("NM_INTRON.1:c.10_(20_30)delAAAA", "c"),
            ("NM_INTRON.1:c.10_?delAAAA", "c"),
            ("NM_INTRON.1:c.10_(20_30)del", "c"),
            ("NM_INTRON.1:c.10_?del", "c"),
            ("NM_INTRON.1:r.*5_?delaaaa", "r"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            assert_end_boundary_refused(
                descriptor,
                coord,
                "with a provider",
                hgvs_to_spdi(&variant, &provider),
            );
        }
    }

    /// **The discriminating case, and the reason this is not #1795's guard
    /// again.** `c.(4185+1_4186-1)_(4357+1_4358-1)del` — the exon-deletion shape
    /// [`crate::hgvs::interval::UncertainBoundary`] names as its motivating
    /// example — carries `+`/`-` offsets *inside* the range boundary, and that
    /// is legitimate HGVS on this axis. The genomic guard refuses an offset
    /// outright; here the offset must be beside the point, so the refusal must
    /// cite the absent coordinate and must not mention it.
    ///
    /// A guard written as "walk both endpoints of the range and refuse an
    /// offset" would pass every assertion in the test above and fail this one,
    /// which is what makes it the discriminating case rather than a restatement.
    #[test]
    fn an_offset_inside_the_range_is_not_what_is_refused() {
        let provider = make_intronic_provider();
        for descriptor in [
            "NM_INTRON.1:c.10_(20+1_21-1)del",
            "NM_INTRON.1:c.10_(20+1_21-1)delAAAA",
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            let err = hgvs_to_spdi(&variant, &provider)
                .expect_err("a range end boundary names no single coordinate");
            let message = err.to_string();
            assert!(
                message.contains("names no single coordinate"),
                "`{descriptor}` must be refused for the absent coordinate: {message}"
            );
            assert!(
                !message.contains("offset"),
                "`{descriptor}` was refused for carrying an offset, but an offset is legitimate \
                 on the `c.` axis — the defect is the absent single coordinate: {message}"
            );
        }
    }

    /// The negative control: a boundary that *does* name a coordinate must keep
    /// converting, on every axis and every entry point that accepted it before.
    ///
    /// `(13)` is the case that discriminates a correct guard from an
    /// over-general one. It is `Mu::Uncertain` — a parenthesised but perfectly
    /// numeric position — so `inner()` answers `Some` and it resolves exactly
    /// like the bare `13` beside it. A guard keyed on "the boundary is
    /// parenthesised", or on `Interval::has_complex_boundaries`, would refuse it
    /// and pass every assertion in the tests above.
    ///
    /// **The denominator is asserted** so a run that converted nothing — the
    /// shape a `0 of 0` pass takes — cannot read as a green negative control.
    #[test]
    fn a_transcript_end_that_names_a_coordinate_still_converts() {
        let provider = make_intronic_provider();
        let both_paths = [
            "NM_INTRON.1:n.10_(13)delAAAA",
            "NM_INTRON.1:n.10_13delAAAA",
            "NM_INTRON.1:n.10delA",
            "NM_INTRON.1:n.10A>G",
            "NM_INTRON.1:r.10_(13)delaaaa",
            "NM_INTRON.1:r.10_13delaaaa",
            "NM_INTRON.1:r.10dela",
        ];
        let provider_only = [
            "NM_INTRON.1:c.10_(13)delAAAA",
            "NM_INTRON.1:c.10_13delAAAA",
            "NM_INTRON.1:c.10delA",
            "NM_INTRON.1:c.10del",
        ];

        let mut converted = 0usize;
        for descriptor in both_paths {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, result) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                result.unwrap_or_else(|e| {
                    panic!("`{descriptor}` must still convert {path}, got {e}")
                });
                converted += 1;
            }
        }
        for descriptor in provider_only {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            hgvs_to_spdi(&variant, &provider)
                .unwrap_or_else(|e| panic!("`{descriptor}` must still convert, got {e}"));
            converted += 1;
        }

        assert_eq!(
            converted,
            both_paths.len() * 2 + provider_only.len(),
            "the negative control converted {converted} descriptions; if this shrinks the guard \
             has over-generalised, and if the loop stops running it proves nothing"
        );
    }

    /// The confluence failure the collapse produced, stated as the invariant
    /// rather than as pinned triples: descriptions that `parse` and `Display`
    /// distinctly must not share one SPDI triple.
    ///
    /// On `main` all three of these converted to `NM_INTRON.1:19:AAAA:`.
    ///
    /// **The denominator is asserted, because with the guard in place the
    /// collision `panic!` is unreachable** — two of the three are refused and
    /// skipped, so `seen` holds one triple and there is no pair left to collide.
    /// That is the `0 of 0` shape, so the census below is what carries the
    /// meaning today, and it goes red the moment an unresolvable end becomes
    /// convertible again — which is exactly when the collision check goes live
    /// and has to be re-read rather than trusted.
    #[test]
    fn unresolvable_transcript_ends_do_not_collapse_onto_a_resolvable_one() {
        /// Only the fully-resolvable spelling converts today.
        const CONVERTIBLE_TODAY: usize = 1;

        let provider = make_intronic_provider();
        let descriptors = [
            "NM_INTRON.1:c.10_(20_30)delAAAA",
            "NM_INTRON.1:c.10_?delAAAA",
            "NM_INTRON.1:c.10_13delAAAA",
        ];
        let mut seen: Vec<(&str, String)> = Vec::new();
        for descriptor in descriptors {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            if let Ok(spdi) = hgvs_to_spdi(&variant, &provider) {
                let triple = spdi.to_string();
                if let Some((other, _)) = seen.iter().find(|(_, t)| *t == triple) {
                    panic!(
                        "`{descriptor}` and `{other}` are different descriptions but share the \
                         triple `{triple}`"
                    );
                }
                seen.push((descriptor, triple));
            }
        }

        assert_eq!(
            seen.len(),
            CONVERTIBLE_TODAY,
            "{} of {} descriptors converted, expected {CONVERTIBLE_TODAY}: {seen:?}. If this \
             grew, an unresolvable end is convertible again and the collision check above has \
             just become live — read what it now compares before re-pinning this number. If it \
             shrank, the loop is comparing nothing at all",
            seen.len(),
            descriptors.len()
        );
    }

    /// An intronic start beside an unresolvable end is refused for the **end**,
    /// which is a deliberate change of diagnostic and worth pinning as one.
    ///
    /// On `main`, `n.10+5_?delAAAA` reported the intronic start
    /// (`UnrepresentableInSpdi`, "cannot be expressed in SPDI without genomic
    /// projection"); it now reports the end. Both are correct refusals, and the
    /// ordering is structural rather than a preference: `resolve_tx_to_provider_tx`
    /// takes a resolved end **by value**, so there is nothing to hand it until
    /// the boundary yields one. Manufacturing a fake end to satisfy that
    /// signature — the start — is the defect being fixed.
    ///
    /// The intronic decline is unchanged where the end *is* resolvable, which is
    /// the second half of this test and the thing a reader will actually want to
    /// know.
    #[test]
    fn an_intronic_start_with_an_unresolvable_end_reports_the_end() {
        let provider = make_intronic_provider();

        let both_unresolvable = parse_hgvs("NM_INTRON.1:n.10+5_?delAAAA").expect("must parse");
        let err = hgvs_to_spdi(&both_unresolvable, &provider)
            .expect_err("neither endpoint has an SPDI representation");
        assert!(
            matches!(err, ConversionError::InvalidPosition { .. }),
            "expected the end-boundary verdict, got {err:?}"
        );
        assert!(
            err.to_string().contains("names no single coordinate"),
            "expected the end-boundary reason, got {err}"
        );

        let intronic_only = parse_hgvs("NM_INTRON.1:n.10+5_20delAAAA").expect("must parse");
        let err = hgvs_to_spdi(&intronic_only, &provider)
            .expect_err("an intronic transcript position has no SPDI representation");
        assert!(
            matches!(err, ConversionError::UnrepresentableInSpdi { .. }),
            "a resolvable end must leave the intronic decline untouched, got {err:?}"
        );
        assert!(
            err.to_string().contains("genomic projection"),
            "the intronic decline lost its own reason: {err}"
        );
    }

    // ------------------------------------------------------------------
    // Complex `(a_b)` boundaries (#1795)
    // ------------------------------------------------------------------

    /// A provider carrying all three genomic axes, so the provider-backed arm
    /// of each test below runs against a populated provider rather than an
    /// empty one.
    ///
    /// **No test here currently reaches a fetch, and the negative control is
    /// the proof**: every one of its rows is asserted to convert identically
    /// through [`hgvs_to_spdi_simple`], which holds no provider at all. That is
    /// because each row spells its own bases (`delACGT`) or its own reference
    /// base (`10C>G`), and [`emit_spdi_for_edit`] consults the provider only
    /// for the *unspelled* arms — a bare `del`/`dup`/`inv`. So the provider is
    /// inert for these rows by construction; it is here so that adding a row
    /// without explicit bases does not also require building a fixture, not
    /// because anything below depends on a fetch succeeding.
    fn three_axis_provider() -> MockProvider {
        let mut provider = MockProvider::new();
        for accession in ["NC_000001.11", "NC_012920.1", "NC_001416.1"] {
            provider.add_genomic_sequence(accession, "ACGTACGTACGTACGTACGTACGTACGT".to_string());
        }
        provider
    }

    /// The #1628 guard reads each boundary through `UncertainBoundary::inner`,
    /// which answers `None` for a `Range` — so a prohibited offset written
    /// inside a complex `(a_b)` boundary was invisible to it and converted.
    ///
    /// This is the same prohibition the simple-position control
    /// (`a_genomic_offset_is_refused_rather_than_dropped`) pins, on the same
    /// three axes and the same two entry points, differing only in that the
    /// offset is written inside a range rather than as the whole boundary.
    /// `checklist.md:16` does not care which of the two it is, and neither
    /// should the guard.
    ///
    /// Both endpoints of the range are exercised — `(20+1_30)` and
    /// `(20_30+1)` — because reading only the near one is the obvious
    /// half-fix, and it passes every assertion that names the first.
    /// A range on the *start* is included too: it was already refused, but for
    /// the wrong reason ("unknown start position"), which diagnoses the
    /// uncertainty and never mentions the prohibited offset that is also there.
    #[test]
    fn a_genomic_offset_inside_a_complex_boundary_is_refused_rather_than_dropped() {
        let provider = three_axis_provider();
        for (descriptor, coord) in [
            ("NC_000001.11:g.10_(20+1_30)delACGT", "g"),
            ("NC_000001.11:g.10_(20-1_30)delACGT", "g"),
            ("NC_000001.11:g.10_(20_30+1)delACGT", "g"),
            ("NC_000001.11:g.10_(20+1_30)insTT", "g"),
            ("NC_000001.11:g.(10+1_11)_20delACGT", "g"),
            ("NC_012920.1:m.10_(20+1_30)delACGT", "m"),
            ("NC_001416.1:o.10_(20+1_30)delACGT", "o"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let err = match converted {
                    Err(err) => err,
                    Ok(spdi) => panic!(
                        "`{descriptor}` converted {path} to `{spdi}`; the offset inside the \
                         complex boundary was dropped"
                    ),
                };
                assert!(
                    matches!(err, ConversionError::InvalidPosition { .. }),
                    "`{descriptor}` {path} must be refused as InvalidPosition, got {err:?}"
                );
                let message = err.to_string();
                assert!(
                    message.contains("carries a +/- offset"),
                    "`{descriptor}` {path} was refused for some other reason: {message}"
                );
                assert!(
                    message.contains(&format!("{coord}. position")),
                    "`{descriptor}` {path} named the wrong coordinate axis: {message}"
                );
            }
        }
    }

    /// The #1643 half of the same guard is blind in exactly the same way: a
    /// `pter`/`qter`/`cen` written inside a complex boundary was never
    /// inspected. Pinned separately from the offset because the two are
    /// different clauses reached through one walk, and a fix that repairs the
    /// walk for one necessarily repairs it for the other — which is only
    /// evidence if both are asserted.
    #[test]
    fn a_genomic_special_position_inside_a_complex_boundary_is_refused() {
        let provider = three_axis_provider();
        for (descriptor, coord) in [
            ("NC_000001.11:g.10_(20_qter)delACGT", "g"),
            ("NC_000001.11:g.10_(cen_30)delACGT", "g"),
            ("NC_012920.1:m.10_(20_qter)delACGT", "m"),
            ("NC_001416.1:o.10_(20_qter)delACGT", "o"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let err = match converted {
                    Err(err) => err,
                    Ok(spdi) => panic!(
                        "`{descriptor}` converted {path} to `{spdi}`; the special position \
                         inside the complex boundary was flattened"
                    ),
                };
                assert!(
                    matches!(err, ConversionError::InvalidPosition { .. }),
                    "`{descriptor}` {path} must be refused as InvalidPosition, got {err:?}"
                );
                let message = err.to_string();
                assert!(
                    message.contains("names no numeric coordinate"),
                    "`{descriptor}` {path} was refused for some other reason: {message}"
                );
                assert!(
                    message.contains(&format!("{coord}. position")),
                    "`{descriptor}` {path} named the wrong coordinate axis: {message}"
                );
            }
        }
    }

    /// The enabling half, and the one with no offset anywhere in it:
    /// `get_end_pos(..).unwrap_or(start_pos)` silently collapsed an
    /// unresolvable **end** onto the start, so `g.10_(20_30)delACGT` and
    /// `g.10_?delACGT` both answered as though they had been written
    /// `g.10delACGT`.
    ///
    /// The start side has always refused (`ok_or_else`), and so does the VCF
    /// sibling on both endpoints — the fallback was the asymmetry, not the
    /// refusal. SPDI positions are exact; an uncertain or unknown boundary has
    /// no exact coordinate to offer, so declining is the same answer the guard
    /// above gives for the same reason.
    ///
    /// Both unresolvable shapes are covered — a `Range` boundary and a
    /// `Single(Unknown)` `?` — because `inner()` answers `None` for both and a
    /// fix keyed on `is_range()` would leave `?` collapsing. Edits that consume
    /// the span and edits that do not (`ins`, `dup`) are both included, since
    /// they read the interval through different arms of `emit_spdi_for_edit`.
    #[test]
    fn an_unresolvable_genomic_end_boundary_is_refused_rather_than_collapsed() {
        let provider = three_axis_provider();
        for (descriptor, coord) in [
            ("NC_000001.11:g.10_(20_30)delACGT", "g"),
            ("NC_000001.11:g.10_?delACGT", "g"),
            ("NC_000001.11:g.10_(20_30)insTT", "g"),
            ("NC_000001.11:g.10_(20_30)dupACGT", "g"),
            ("NC_012920.1:m.10_(20_30)delACGT", "m"),
            ("NC_012920.1:m.10_?delACGT", "m"),
            ("NC_001416.1:o.10_(20_30)delACGT", "o"),
            ("NC_001416.1:o.10_?delACGT", "o"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let err = match converted {
                    Err(err) => err,
                    Ok(spdi) => panic!(
                        "`{descriptor}` converted {path} to `{spdi}`; the end boundary was \
                         collapsed onto the start position"
                    ),
                };
                assert!(
                    matches!(err, ConversionError::InvalidPosition { .. }),
                    "`{descriptor}` {path} must be refused as InvalidPosition, got {err:?}"
                );
                let message = err.to_string();
                assert!(
                    message.contains("names no single coordinate"),
                    "`{descriptor}` {path} was refused for some other reason: {message}"
                );
                assert!(
                    message.contains(&format!("{coord}. end boundary")),
                    "`{descriptor}` {path} named the wrong coordinate axis: {message}"
                );
            }
        }
    }

    /// The discriminating half: an end boundary that *does* name a coordinate
    /// must keep converting, and refusing every parenthesised boundary is the
    /// obvious over-generalisation that would pass all three tests above.
    ///
    /// `(13)` is `Mu::Uncertain` — the author is unsure the position is exactly
    /// 13, but 13 is the coordinate they wrote and `inner()` returns it. That
    /// is a different thing from `(12_14)`, which names a *region* and no
    /// single position, and the two must not be conflated because they share a
    /// pair of parentheses.
    #[test]
    fn a_resolvable_genomic_end_boundary_still_converts() {
        let provider = three_axis_provider();
        for (descriptor, expected) in [
            ("NC_000001.11:g.10_13delACGT", "NC_000001.11:9:ACGT:"),
            ("NC_000001.11:g.10_(13)delACGT", "NC_000001.11:9:ACGT:"),
            ("NC_000001.11:g.(10)_(13)delACGT", "NC_000001.11:9:ACGT:"),
            ("NC_000001.11:g.10C>G", "NC_000001.11:9:C:G"),
            ("NC_012920.1:m.10_13delACGT", "NC_012920.1:9:ACGT:"),
            ("NC_001416.1:o.10_13delACGT", "NC_001416.1:9:ACGT:"),
        ] {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            for (path, converted) in [
                ("without a provider", hgvs_to_spdi_simple(&variant)),
                ("with a provider", hgvs_to_spdi(&variant, &provider)),
            ] {
                let spdi = converted
                    .unwrap_or_else(|err| panic!("`{descriptor}` {path} must convert: {err}"));
                assert_eq!(
                    spdi.to_string(),
                    expected,
                    "`{descriptor}` {path} moved to a different triple"
                );
            }
        }
    }

    /// The confluence failure #1628 and #1729 were filed to stop, back on this
    /// shape: five descriptions that `parse` and `Display` keep distinct all
    /// converted to `NC_000001.11:9:ACGT:`. Measured on `origin/main` at
    /// `cc8407bc` before the fix.
    ///
    /// Written as the invariant — no two of them may share a triple — rather
    /// than as five pinned errors, so it keeps meaning something if a future
    /// change makes any of these resolvable. As with
    /// `special_positions_do_not_collapse_onto_one_another`, the denominator is
    /// asserted, because with the fix in place four of the five are refused and
    /// the collision check has nothing left to compare: `0 of 0` must not read
    /// as a pass.
    #[test]
    fn complex_boundaries_do_not_collapse_onto_the_offset_free_spelling() {
        /// Only the fully-determined spelling converts once the fix is in.
        const CONVERTIBLE_TODAY: usize = 1;

        let provider = three_axis_provider();
        let descriptors = [
            "NC_000001.11:g.10_(20+1_30)delACGT",
            "NC_000001.11:g.10_(20+5_30)delACGT",
            "NC_000001.11:g.10_(20-1_30)delACGT",
            "NC_000001.11:g.10_(20_30)delACGT",
            "NC_000001.11:g.10delACGT",
        ];

        // The premise: these are five distinct descriptions, not five
        // spellings the parser has already unified. If this ever fails, the
        // collapse is happening upstream of the conversion and the rest of
        // this test is measuring the wrong component.
        let mut displayed: Vec<String> = descriptors
            .iter()
            .map(|d| parse_hgvs(d).expect("fixture must parse").to_string())
            .collect();
        displayed.sort();
        displayed.dedup();
        assert_eq!(
            displayed.len(),
            descriptors.len(),
            "the descriptions do not survive parse/Display distinctly: {displayed:?}"
        );

        let mut seen: Vec<(&str, String)> = Vec::new();
        for descriptor in descriptors {
            let variant = parse_hgvs(descriptor).expect("fixture must parse");
            if let Ok(spdi) = hgvs_to_spdi(&variant, &provider) {
                let triple = spdi.to_string();
                if let Some((other, _)) = seen.iter().find(|(_, t)| *t == triple) {
                    panic!(
                        "`{descriptor}` and `{other}` are different descriptions but share \
                         the triple `{triple}`"
                    );
                }
                seen.push((descriptor, triple));
            }
        }

        assert_eq!(
            seen.len(),
            CONVERTIBLE_TODAY,
            "{} of {} descriptors converted, expected {CONVERTIBLE_TODAY}: {seen:?}. \
             If this grew, a complex boundary is convertible again and the collision check \
             above has just become live — read what it now compares before re-pinning this \
             number. If it shrank, `g.10delACGT` stopped converting and the loop is \
             comparing nothing at all",
            seen.len(),
            descriptors.len()
        );
    }
}