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
//! HGVS variant types
//!
//! The main variant enum and supporting types for representing
//! complete HGVS variant descriptions.

use super::edit::{NaEdit, ProteinEdit};
use super::interval::{CdsInterval, GenomeInterval, ProtInterval, RnaInterval, TxInterval};
use super::uncertainty::Mu;
use serde::{Deserialize, Serialize};
use smol_str::{SmolStr, SmolStrBuilder};
use std::fmt;
use std::sync::Arc;

/// Interned accession prefixes for common RefSeq and Ensembl types.
/// Using static `Arc<str>` avoids allocating new strings for common prefixes.
mod interned {
    use std::sync::{Arc, OnceLock};

    macro_rules! interned_prefix {
        ($name:ident, $value:literal) => {
            pub fn $name() -> Arc<str> {
                static INSTANCE: OnceLock<Arc<str>> = OnceLock::new();
                INSTANCE.get_or_init(|| Arc::from($value)).clone()
            }
        };
    }

    // RefSeq prefixes
    interned_prefix!(nc, "NC");
    interned_prefix!(ng, "NG");
    interned_prefix!(nt, "NT");
    interned_prefix!(nw, "NW");
    interned_prefix!(nm, "NM");
    interned_prefix!(nr, "NR");
    interned_prefix!(np, "NP");
    interned_prefix!(xm, "XM");
    interned_prefix!(xr, "XR");
    interned_prefix!(xp, "XP");

    // Ensembl prefixes
    interned_prefix!(enst, "ENST");
    interned_prefix!(ensg, "ENSG");
    interned_prefix!(ensp, "ENSP");
    interned_prefix!(ense, "ENSE");
    interned_prefix!(ensr, "ENSR");

    // LRG prefix
    interned_prefix!(lrg, "LRG");

    // Empty string for assembly refs
    interned_prefix!(empty, "");

    /// Get an interned prefix if available, otherwise return None
    #[inline]
    pub fn get_prefix(s: &str) -> Option<Arc<str>> {
        match s {
            "NC" => Some(nc()),
            "NG" => Some(ng()),
            "NT" => Some(nt()),
            "NW" => Some(nw()),
            "NM" => Some(nm()),
            "NR" => Some(nr()),
            "NP" => Some(np()),
            "XM" => Some(xm()),
            "XR" => Some(xr()),
            "XP" => Some(xp()),
            "ENST" => Some(enst()),
            "ENSG" => Some(ensg()),
            "ENSP" => Some(ensp()),
            "ENSE" => Some(ense()),
            "ENSR" => Some(ensr()),
            "LRG" => Some(lrg()),
            "" => Some(empty()),
            _ => None,
        }
    }
}

/// Accession number with optional version
///
/// The `prefix`, `assembly`, and `chromosome` fields use `Arc<str>` internally for
/// cheap cloning - these strings are frequently cloned during parsing and
/// normalization, and `Arc<str>` reduces this to a simple reference count increment.
/// The `number` field is a `SmolStr`, which inlines short strings (no heap
/// allocation) while still cloning cheaply (see its field doc below).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Accession {
    /// Accession prefix (e.g., "NC", "NM", "NP", "ENST")
    pub prefix: Arc<str>,
    /// Accession number
    ///
    /// `SmolStr` inlines strings up to 23 bytes (every real accession number
    /// qualifies), so the number is stored without a heap allocation. It still
    /// clones cheaply and serializes identically to a plain string.
    pub number: SmolStr,
    /// Version number (e.g., .3 in NM_000088.3)
    pub version: Option<u32>,
    /// Whether this is an Ensembl-style accession (no underscore separator)
    #[serde(default)]
    pub ensembl_style: bool,
    /// Assembly name (e.g., "GRCh37", "GRCh38") for assembly/chromosome notation
    #[serde(default)]
    pub assembly: Option<Arc<str>>,
    /// Chromosome name (e.g., "chr1", "chr23") for assembly/chromosome notation
    #[serde(default)]
    pub chromosome: Option<Arc<str>>,
    /// Genomic context accession for compound reference syntax
    /// e.g., NC_000013.11 in NC_000013.11(NM_004119.3):c.…
    #[serde(default)]
    pub genomic_context: Option<Box<Accession>>,
}

impl Accession {
    /// Intern a prefix string, using a static Arc if available
    #[inline]
    fn intern_prefix(prefix: impl AsRef<str> + Into<Arc<str>>) -> Arc<str> {
        // Look up the interned static *before* allocating: for the common known
        // prefixes (NC/NM/NP/ENST/…) this avoids allocating an `Arc<str>` on every
        // parse just to discard it for the static. Only unknown prefixes allocate.
        interned::get_prefix(prefix.as_ref()).unwrap_or_else(|| prefix.into())
    }

    pub fn new(
        prefix: impl AsRef<str> + Into<Arc<str>>,
        number: impl Into<SmolStr>,
        version: Option<u32>,
    ) -> Self {
        let prefix = Self::intern_prefix(prefix);
        let ensembl_style = Self::is_ensembl_prefix(&prefix);
        // LRG accessions never carry a version per HGVS spec (SVD-WG008).
        // Drop any provided version so Display canonicalizes to the spec form.
        let version = if Self::is_lrg_prefix(&prefix) {
            None
        } else {
            version
        };
        Self {
            prefix,
            number: number.into(),
            version,
            ensembl_style,
            assembly: None,
            chromosome: None,
            genomic_context: None,
        }
    }

    /// Create with explicit Ensembl style setting
    pub fn with_style(
        prefix: impl AsRef<str> + Into<Arc<str>>,
        number: impl Into<SmolStr>,
        version: Option<u32>,
        ensembl_style: bool,
    ) -> Self {
        let prefix = Self::intern_prefix(prefix);
        // LRG accessions never carry a version per HGVS spec (SVD-WG008).
        let version = if Self::is_lrg_prefix(&prefix) {
            None
        } else {
            version
        };
        Self {
            prefix,
            number: number.into(),
            version,
            ensembl_style,
            assembly: None,
            chromosome: None,
            genomic_context: None,
        }
    }

    /// Create an assembly/chromosome reference (e.g., GRCh37(chr23))
    pub fn from_assembly(assembly: impl Into<Arc<str>>, chromosome: impl Into<Arc<str>>) -> Self {
        Self {
            prefix: interned::empty(),
            number: SmolStr::default(),
            version: None,
            ensembl_style: false,
            assembly: Some(assembly.into()),
            chromosome: Some(chromosome.into()),
            genomic_context: None,
        }
    }

    /// Create a compound reference with genomic context
    /// e.g., NC_000013.11(NM_004119.3) where `context` is NC_000013.11
    /// and the primary accession is NM_004119.3
    pub fn with_genomic_context(mut self, context: Accession) -> Self {
        self.genomic_context = Some(Box::new(context));
        self
    }

    /// Drop any genomic context, returning the bare accession (e.g.
    /// `NG_007485.1(NM_058195.3)` → `NM_058195.3`). The inverse of
    /// [`Self::with_genomic_context`].
    pub fn without_genomic_context(mut self) -> Self {
        self.genomic_context = None;
        self
    }

    /// Check if this is an assembly/chromosome style reference
    pub fn is_assembly_ref(&self) -> bool {
        self.assembly.is_some() && self.chromosome.is_some()
    }

    /// Check if a prefix is an Ensembl-style prefix.
    ///
    /// Ensembl stable IDs have the shape `ENS<species_code><feature>` where:
    /// - `species_code` is 0–5 uppercase letters (`""` for human, `MUS` for
    ///   mouse, `RNO` for rat, `BTA` for cow, `DAR` for zebrafish, `CAF`
    ///   for dog, `SSC` for pig, etc.).
    /// - `feature` is one of `G` (gene), `T` (transcript), `P` (peptide),
    ///   `E` (exon), or `R` (regulatory).
    ///
    /// Examples that match: `ENST`, `ENSP`, `ENSMUST`, `ENSMUSG`,
    /// `ENSRNOT`, `ENSBTAG`, `ENSDARP`.
    ///
    /// Reference: <https://useast.ensembl.org/info/genome/stable_ids/index.html>.
    pub fn is_ensembl_prefix(prefix: &str) -> bool {
        // Must start with "ENS" and have at least one feature letter after it.
        let Some(body) = prefix.strip_prefix("ENS") else {
            return false;
        };
        if body.is_empty() {
            return false;
        }
        // body = species_code + feature. Per the Ensembl stable-ID convention
        // the species code is 0..=5 uppercase letters and the feature is 1
        // letter, so body must be at most 6 chars. This rejects arbitrarily
        // long uppercase prefixes that would otherwise pass the suffix check.
        if body.len() > 6 {
            return false;
        }
        // All characters in the body must be uppercase ASCII letters.
        if !body.chars().all(|c| c.is_ascii_uppercase()) {
            return false;
        }
        // The last letter is the feature suffix.
        matches!(
            body.as_bytes()[body.len() - 1],
            b'G' | b'T' | b'P' | b'E' | b'R'
        )
    }

    /// Check if this accession is an Ensembl accession
    pub fn is_ensembl(&self) -> bool {
        self.ensembl_style || Self::is_ensembl_prefix(&self.prefix)
    }

    /// Map an Ensembl-style prefix to the HGVS coordinate type its feature
    /// implies, if any — species-independently.
    ///
    /// Ensembl stable IDs are `ENS<species_code><feature>` (see
    /// [`is_ensembl_prefix`](Self::is_ensembl_prefix)); the *feature* is the
    /// body suffix after the species code and fixes the coordinate type
    /// regardless of the species code (so `ENST`, `ENSMUST`, `ENSRNOT` all map
    /// alike):
    /// - `T` (transcript) → `Some("c")` — coding is the primary type, matching
    ///   the RefSeq `NM_` convention (see [`inferred_variant_type`]).
    /// - `G` (gene, genomic) → `Some("g")`.
    /// - `P` (peptide) → `Some("p")`.
    /// - `E` (exon), `R` (regulatory) → `None`: these are not variant
    ///   references and have no HGVS coordinate type.
    ///
    /// Most features are a single letter, but a few are multi-letter and must
    /// not be classified by their final letter alone. The gene-tree feature
    /// `GT` (Compara, `ENSGT…`) ends in `T` but is **not** a transcript, so it
    /// is rejected explicitly before the single-letter dispatch. (`FM`, protein
    /// family, ends in `M` and is already rejected by `is_ensembl_prefix`.)
    ///
    /// Returns `None` for any non-Ensembl prefix.
    ///
    /// [`inferred_variant_type`]: Self::inferred_variant_type
    fn ensembl_feature_variant_type(prefix: &str) -> Option<&'static str> {
        if !Self::is_ensembl_prefix(prefix) {
            return None;
        }
        // `is_ensembl_prefix` guarantees an "ENS" prefix with a non-empty,
        // all-uppercase-ASCII body, so this slice and the trailing-byte index
        // below are both safe.
        let body = &prefix["ENS".len()..];
        if body.ends_with("GT") {
            // Compara gene tree (`ENSGT…`) — not a variant reference. Guard
            // before the single-letter dispatch so its trailing `T` is not
            // misread as a transcript.
            return None;
        }
        match body.as_bytes()[body.len() - 1] {
            b'T' => Some("c"),
            b'G' => Some("g"),
            b'P' => Some("p"),
            _ => None, // E (exon), R (regulatory): not variant references.
        }
    }

    /// Check if a prefix is an Ensembl **transcript** prefix (feature `T`),
    /// species-independently: `ENST` (human), `ENSMUST` (mouse), `ENSRNOT`
    /// (rat), `ENSBTAT` (cow), etc.
    ///
    /// This is the transcript-only refinement of
    /// [`is_ensembl_prefix`](Self::is_ensembl_prefix) (which accepts any Ensembl
    /// feature). It is the shared basis for classifying Ensembl transcript
    /// references in [`is_transcript_reference`](Self::is_transcript_reference).
    pub fn is_ensembl_transcript_prefix(prefix: &str) -> bool {
        Self::ensembl_feature_variant_type(prefix) == Some("c")
    }

    /// Check if a prefix is the canonical LRG prefix (`"LRG"`, uppercase).
    ///
    /// Per HGVS spec the LRG prefix is case-sensitive (lowercase `lrg_` is not
    /// recognized as an LRG accession; it parses as a generic chromosome
    /// name). See `assets/hgvs-nomenclature/docs/background/refseq.md`.
    pub fn is_lrg_prefix(prefix: &str) -> bool {
        prefix == "LRG"
    }

    /// Check if this accession is an LRG accession.
    pub fn is_lrg(&self) -> bool {
        Self::is_lrg_prefix(&self.prefix)
    }

    /// Validate Ensembl accession format
    /// Returns true if valid, false if invalid
    pub fn validate_ensembl(&self) -> bool {
        if !self.is_ensembl() {
            return true; // Not an Ensembl ID, skip validation
        }
        // Ensembl IDs should have 11-15 digit numbers
        let digit_count = self.number.len();
        (11..=15).contains(&digit_count) && self.number.chars().all(|c| c.is_ascii_digit())
    }

    /// Infer the *primary* expected variant coordinate type from the accession
    /// prefix and (for LRG) the trailing discriminator inside `number`.
    ///
    /// This is informational, not a validator: it returns the canonical
    /// coordinate type for the accession class. The accession may legally
    /// appear with other coordinate types in the variant block — for
    /// example, `NM_*` always returns `"c"` even though `NM_*:n.…` and
    /// `NM_*:r.…` parse correctly, and `LRG_<N>t<M>` always returns `"c"`
    /// even though `LRG_<N>t<M>:n.…` (non-coding) and
    /// `LRG_<N>t<M>:r.…` (RNA) are valid per the HGVS spec.
    ///
    /// LRG accessions take three forms (see https://www.lrg-sequence.org/faq/
    /// and `assets/hgvs-nomenclature/docs/background/refseq.md`):
    /// - `LRG_<N>`        — the LRG genomic record itself; uses `g.` coordinates.
    /// - `LRG_<N>t<M>`    — transcript M of LRG_N; primary `c.` (coding).
    /// - `LRG_<N>p<M>`    — protein M of LRG_N; uses `p.` coordinates.
    ///
    /// The `t<M>` / `p<M>` discriminator is captured inside `self.number`
    /// (e.g. `prefix="LRG"`, `number="1t1"`), so the dispatch must inspect the
    /// trailing discriminator rather than only the prefix.
    pub fn inferred_variant_type(&self) -> Option<&'static str> {
        // Ensembl accessions dispatch on their feature letter, species-
        // independently (#1057): ENST/ENSMUST/… → c, ENSG/ENSMUSG/… → g,
        // ENSP/… → p; exon (E) / regulatory (R) features are not variant
        // references and infer nothing.
        if let Some(variant_type) = Self::ensembl_feature_variant_type(&self.prefix) {
            return Some(variant_type);
        }
        match &*self.prefix {
            // RefSeq genomic
            "NC" | "NG" | "NT" | "NW" => Some("g"),
            // RefSeq transcript/mRNA
            "NM" => Some("c"),
            // RefSeq non-coding RNA
            "NR" => Some("n"),
            // RefSeq protein
            "NP" => Some("p"),
            // LRG: dispatch on the t<M> / p<M> discriminator captured in `number`.
            // See `is_lrg_prefix` / `is_lrg` for the prefix-class predicate.
            p if Self::is_lrg_prefix(p) => Some(Self::lrg_inferred_variant_type(&self.number)),
            // UniProt protein (single letter prefix: O, P, Q, A-N, R-Z)
            p if p.len() == 1 && p.chars().next().is_some_and(|c| c.is_ascii_uppercase()) => {
                Some("p")
            }
            _ => None,
        }
    }

    /// Map an LRG `number` field (e.g. `"1"`, `"1t1"`, `"1p1"`) to its variant type.
    ///
    /// The discriminator is `t<digits>` for transcripts (coding, `c.`) or
    /// `p<digits>` for protein products (`p.`). A bare numeric `number`
    /// (the LRG record itself) maps to genomic (`g.`). Any malformed input
    /// falls back to `g`, matching the prior behavior for unrecognized shapes.
    fn lrg_inferred_variant_type(number: &str) -> &'static str {
        let bytes = number.as_bytes();
        // Find the discriminator letter, if any. A valid LRG number is one or
        // more digits, optionally followed by `t` or `p` and one or more digits.
        let disc_pos = bytes.iter().position(|&b| b == b't' || b == b'p');
        match disc_pos {
            None => "g",
            Some(pos) => {
                // Validate: digits before, digits after, no further non-digits.
                let before_ok = pos > 0 && bytes[..pos].iter().all(|b| b.is_ascii_digit());
                let after = &bytes[pos + 1..];
                let after_ok = !after.is_empty() && after.iter().all(|b| b.is_ascii_digit());
                if before_ok && after_ok {
                    if bytes[pos] == b't' {
                        "c"
                    } else {
                        "p"
                    }
                } else {
                    // Malformed discriminator — be conservative and treat as genomic.
                    "g"
                }
            }
        }
    }

    /// Check if this is a UniProt accession
    pub fn is_uniprot(&self) -> bool {
        // UniProt: single uppercase letter prefix, 5-character number, no version
        self.prefix.len() == 1
            && self
                .prefix
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_uppercase())
            && self.number.len() == 5
            && self.number.chars().all(|c| c.is_ascii_alphanumeric())
    }

    /// Returns true if this accession is a non-coding RNA transcript reference
    /// (`NR_` curated or `XR_` predicted). Such references have no CDS and are
    /// not genomic, so only `n.` and `r.` coordinate systems are valid on them
    /// (a `c.`/`g.`/`m.`/`o.` description is a coordinate-system mismatch — #486).
    pub fn is_noncoding_rna(&self) -> bool {
        matches!(&*self.prefix, "NR" | "XR")
    }

    /// Returns true if this accession is a **transcript-level** reference that
    /// fully specifies `c.`/`n.`/`r.` coordinates on its own: RefSeq mRNA/ncRNA
    /// (`NM`/`NR`/`XM`/`XR`), an Ensembl transcript (`ENST`, `ENSMUST`,
    /// `ENSRNOT`, … — any species, per #1057), or an LRG transcript
    /// (`LRG_<N>t<M>`).
    ///
    /// This is **one of several** conditions behind the gene-symbol selector's
    /// Display policy (#1051); [`Self::admits_gene_selector`] is the
    /// accession-level predicate, and it also suppresses the selector on a
    /// compound reference (#1139). Per HGVS Nomenclature (`refseq.md`), the
    /// parenthetical after a reference sequence is a *specification* whose
    /// accepted values are transcript/protein **accessions**, not gene symbols —
    /// and a transcript reference needs no such specification at all (bare
    /// `NM_…:c.…` is the canonical form). So when the reference is itself a
    /// transcript, the gene-symbol selector is disallowed and Display drops it.
    /// Genomic (`NC`/`NG`/`NT`/`NW`/`ENSG`/bare `LRG_<N>`), mitochondrial,
    /// protein, and unclassifiable (custom) references are **not** transcript
    /// references: for them this check alone does not drop the selector — it is
    /// either the spec-sanctioned exception (a gene with no transcript, e.g.
    /// mitochondrial) or a value ferro cannot safely drop.
    ///
    /// **This predicate answers only the transcript-vs-not question.** It is not
    /// the whole selector policy: the `p.` axis takes no gene-symbol selector on
    /// **any** accession (#310/#1142), which the render sites enforce by
    /// coordinate type rather than by reference class. The two rules can
    /// disagree — a mitochondrial `m.` description keeps its selector while a
    /// mitochondrial *protein* (`YP_…:p.…`) does not — so do not read a `false`
    /// here as "the selector is emitted".
    ///
    /// The check is on `self` only — a compound reference such as
    /// `NC_(NM_)(GENE)` stores the transcript (`NM`) as `self` with the genomic
    /// parent in `genomic_context`, so it is correctly classified as a
    /// transcript reference. Note that a compound reference drops the selector
    /// regardless of what its inner accession is: `NC_(NG_)(GENE)` renders as
    /// `NC_(NG_)` even though `NG_` is not a transcript reference, because
    /// [`Self::admits_gene_selector`] also rejects a spent specification slot.
    pub fn is_transcript_reference(&self) -> bool {
        match &*self.prefix {
            "NM" | "NR" | "XM" | "XR" => true,
            // Any Ensembl transcript, species-independently (#1057): ENST,
            // ENSMUST, ENSRNOT, … — but not ENSG/ENSP (gene/protein).
            p if Self::is_ensembl_transcript_prefix(p) => true,
            p if Self::is_lrg_prefix(p) => Self::lrg_inferred_variant_type(&self.number) == "c",
            _ => false,
        }
    }

    /// Returns true if a gene-symbol selector set alongside this accession is
    /// rendered by `Display`.
    ///
    /// Per `refseq.md:40-41` a reference sequence admits **one** parenthesised
    /// specification, and a gene symbol is not an accepted value for it. ferro
    /// therefore emits the selector only where it is the accession's *sole*
    /// specification and cannot be dropped safely — which rules out two cases:
    ///
    /// - a **transcript reference** ([`Self::is_transcript_reference`]), which
    ///   is fully specified on its own and takes no specification (#1051);
    /// - an accession that already carries a `genomic_context`, i.e. a compound
    ///   `genomic(transcript)` reference (#1139). It has already spent its one
    ///   permitted specification, so a selector would render as a second,
    ///   stacked group — `Template(Template-gene.1)(GENE1):c.…` — which is both
    ///   non-conformant and unparseable by ferro's own parser. The
    ///   [`Self::is_transcript_reference`] check alone does not cover this: it
    ///   is a prefix whitelist, so a **custom** (non-RefSeq, non-Ensembl) inner
    ///   accession falls through it.
    ///
    /// Everything else preserves the selector: genomic references where the gene
    /// stands in for a transcript, the spec-sanctioned mitochondrial exception,
    /// and unclassifiable custom references. The value always remains on the
    /// struct for programmatic access, independent of Display.
    ///
    /// **Assembly references keep their selector, by design** (#1145). An
    /// assembly/chromosome reference ([`Self::is_assembly_ref`], e.g.
    /// `GRCh38(chr1)`) renders its parenthesised group from the
    /// `assembly`/`chromosome` fields, and that group is part of the *reference
    /// identifier* — an assembly alone names no sequence — not a specification
    /// in the `refseq.md:38` sense. So `GRCh38(chr1)(BRCA1):g.…` is
    /// `<identifier>(<selector>)`: one specification, the structural analogue of
    /// the preserved `NC_000023.10(DMD):c.…`, and **not** a stacked
    /// `(...)(...)`. Testing `genomic_context` rather than the rendered parens is
    /// what keeps the two apart. (The form itself is a ferro extension for
    /// tolerated legacy input; the spec declines genome-build references outright
    /// — `refseq.md:222-231`.)
    pub(crate) fn admits_gene_selector(&self) -> bool {
        !self.is_transcript_reference() && self.genomic_context.is_none()
    }

    /// Returns true if this is a known human mitochondrial reference accession.
    ///
    /// `NC_012920` is the GRCh38 rCRS mitochondrion; `NC_001807` is the older
    /// (deprecated but still seen) rCRS draft. HGVS requires the `m.` coordinate
    /// system for these accessions, so `normalize()` coerces a `g.` variant on
    /// one of them to `m.`.
    pub fn is_mitochondrial(&self) -> bool {
        let prefix: &str = self.prefix.as_ref();
        let number: &str = self.number.as_ref();
        matches!((prefix, number), ("NC", "012920") | ("NC", "001807"))
    }

    /// Full accession string without version
    pub fn base(&self) -> String {
        collect_written(|out| self.write_base(out))
    }

    /// Full accession string with version if present
    pub fn full(&self) -> String {
        collect_written(|out| self.write_full(out))
    }

    /// [`Self::full`] as a [`SmolStr`], for the callers that only *hold* the
    /// rendered accession to compare it.
    ///
    /// `SmolStr` inlines up to 23 bytes, and every real accession fits —
    /// `NM_000088.3` is 11, `ENST00000357033.8` is 17 — so this renders without
    /// touching the heap where `full()` allocates a `String` every time. Only a
    /// compound `genomic(transcript)` reference spills, and that falls back to
    /// exactly what `full()` would have done. Equality and ordering are the
    /// str's, so a `SmolStr` key compares identically to the `String` it replaces.
    pub(crate) fn full_smol(&self) -> SmolStr {
        collect_written_smol(|out| self.write_full(out))
    }

    /// [`Self::base`], written straight into `out` rather than through a
    /// temporary `String`.
    ///
    /// The single source of truth for `base()`; see [`Self::write_full`] for why
    /// the two are written this way round.
    fn write_base(&self, out: &mut impl fmt::Write) -> fmt::Result {
        // Assembly/chromosome notation: GRCh37(chr23)
        if let (Some(assembly), Some(chromosome)) = (&self.assembly, &self.chromosome) {
            return write!(out, "{assembly}({chromosome})");
        }
        // Compound reference: context(base)
        if let Some(ctx) = &self.genomic_context {
            ctx.write_full(out)?;
            out.write_char('(')?;
            self.write_bare(out)?;
            return out.write_char(')');
        }
        self.write_bare(out)
    }

    /// [`Self::full`], written straight into `out` rather than through a
    /// temporary `String`.
    ///
    /// This is the source of truth for both `full()` and `Display`, and the
    /// direction matters for cost. `Display` used to be
    /// `write!(f, "{}", self.full())`, so **rendering any variant heap-allocated
    /// one `String` per accession it printed** — including the recursive
    /// `genomic_context.full()` — only to copy it into the formatter and drop it.
    /// Every `HgvsVariant::to_string()` paid that, which is a hot path for any
    /// caller normalizing in bulk: it measured 2.5% of
    /// `cis_confluence_axis::three_prime_confluence_census` (47 392
    /// normalizations) on its own, and `member_span`'s call added another 2.3%.
    ///
    /// `fmt::Formatter` implements `fmt::Write`, so one generic writer serves the
    /// allocating and non-allocating callers alike and the two cannot drift.
    ///
    /// **Format specs are ignored, before and after — this changes nothing there,
    /// and the reasoning that said otherwise was wrong.** The obvious worry about
    /// writing pieces straight into `f` is that a spec applied to the whole is
    /// lost: `write_str`/`write_char` bypass `Formatter::pad`, so
    /// `format!("{accession:>20}")` cannot right-align and `{accession:.4}` cannot
    /// truncate. True, and true of the old body as well. `write!(f, "{}", s)`
    /// expands to `f.write_fmt(format_args!("{}", s))`, which renders `s` under the
    /// *inner* format string's specs — and `"{}"` carries none. Only `f.pad(s)`, or
    /// `Display::fmt(&s, f)` reached directly, consults the outer `f`. Measured
    /// three ways rather than reasoned about: `write!(f, "{}", s)` and a
    /// piecewise writer both render `{:>20}` unpadded and `{:.4}` untruncated,
    /// while `f.pad(s)` right-aligns and truncates to `NM_0`.
    ///
    /// So this is a pure refactor at the seam, which is the stronger claim and the
    /// one to make. `test_accession_display` pins the inertness of `{:>20}`,
    /// `{:*^20}`, `{:.4}` and `{:<8.2}` so the question is settled in a test rather
    /// than re-litigated from the shape of the code — it is long-standing behaviour
    /// this crate shares with nearly every multi-field `Display` it defines,
    /// `HgvsVariant`'s included, and no caller in `src/`, `tests/` or `examples/`
    /// applies a spec to an accession or a variant anyway.
    fn write_full(&self, out: &mut impl fmt::Write) -> fmt::Result {
        // Assembly/chromosome notation doesn't have versions
        if self.is_assembly_ref() {
            return self.write_base(out);
        }
        // Compound reference: context(full)
        if let Some(ctx) = &self.genomic_context {
            ctx.write_full(out)?;
            out.write_char('(')?;
            self.write_versioned(out)?;
            return out.write_char(')');
        }
        self.write_versioned(out)
    }

    /// `prefix[_]number`, the accession without version or wrapper.
    fn write_bare(&self, out: &mut impl fmt::Write) -> fmt::Result {
        out.write_str(&self.prefix)?;
        if !self.ensembl_style {
            out.write_char('_')?;
        }
        out.write_str(&self.number)
    }

    /// [`Self::write_bare`] plus `.version`, when there is one.
    fn write_versioned(&self, out: &mut impl fmt::Write) -> fmt::Result {
        self.write_bare(out)?;
        match self.version {
            Some(v) => write!(out, ".{v}"),
            None => Ok(()),
        }
    }

    /// Returns the bare accession string for provider/transcript lookups,
    /// stripping any genomic context wrapper. For compound references like
    /// `NC_000013.11(NM_004119.3)`, this returns just `"NM_004119.3"`.
    pub fn transcript_accession(&self) -> String {
        collect_written(|out| self.write_transcript_accession(out))
    }

    /// [`Self::transcript_accession`] as a [`SmolStr`], for the provider lookups
    /// on the normalization hot path.
    ///
    /// Same reasoning as [`Self::full_smol`]: a provider key is used as a `&str`
    /// and never mutated, so the inline form serves every caller while skipping
    /// the allocation. Both spellings share
    /// [`Self::write_transcript_accession`], so they cannot drift.
    pub(crate) fn transcript_accession_smol(&self) -> SmolStr {
        collect_written_smol(|out| self.write_transcript_accession(out))
    }

    /// [`Self::transcript_accession`], written straight into `out`.
    ///
    /// The single source of truth for both the `String` and the [`SmolStr`]
    /// spelling, in the same style as [`Self::write_full`].
    fn write_transcript_accession(&self, out: &mut impl fmt::Write) -> fmt::Result {
        // Assembly/chromosome notation (e.g. GRCh38(chr1)) uses base() directly
        if self.is_assembly_ref() {
            return self.write_base(out);
        }
        self.write_versioned(out)
    }
}

/// Run a `fmt::Write` producer into a fresh `String`.
///
/// The accession writers below are shared with `Display`, which hands them a
/// `fmt::Formatter`; this is the adapter for the callers that still want an owned
/// `String`. Writing into a `String` cannot fail — `fmt::Write for String` is
/// infallible — so the `Result` is asserted rather than propagated.
///
/// The capacity hint is load-bearing rather than a flourish. The writers push
/// their pieces one at a time, so without it a rendered accession reallocates two
/// or three times where the `format!` these replaced sized the buffer once — which
/// would trade `Display`'s saved allocation for extra ones on the [`Accession::full`]
/// path, and both are hot. 40 bytes covers every real accession, versioned
/// (`NM_000088.3` is 11, `ENST00000357033.8` is 17) and assembly-style
/// (`GRCh38(chr1)` is 12); only a compound `genomic(transcript)` reference can
/// exceed it, and that grows once.
fn collect_written(produce: impl FnOnce(&mut String) -> fmt::Result) -> String {
    /// Enough for any single accession, so the common case never reallocates.
    const TYPICAL_ACCESSION_LEN: usize = 40;
    let mut out = String::with_capacity(TYPICAL_ACCESSION_LEN);
    produce(&mut out).expect("writing into a String is infallible");
    out
}

/// [`collect_written`]'s counterpart for the callers that want a [`SmolStr`].
///
/// `SmolStrBuilder` accumulates into a stack buffer and only spills to a
/// `String` if the total exceeds the inline capacity, so an accession that fits
/// — every real one — is rendered with no allocation at all. Writing into it
/// cannot fail, so the `Result` is asserted rather than propagated, exactly as
/// above.
fn collect_written_smol(produce: impl FnOnce(&mut SmolStrBuilder) -> fmt::Result) -> SmolStr {
    let mut out = SmolStrBuilder::new();
    produce(&mut out).expect("writing into a SmolStrBuilder is infallible");
    out.finish()
}

impl fmt::Display for Accession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.write_full(f)
    }
}

/// Location and edit combined
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct LocEdit<L, E> {
    pub location: L,
    pub edit: Mu<E>,
}

impl<L, E> LocEdit<L, E> {
    pub fn new(location: L, edit: E) -> Self {
        Self {
            location,
            edit: Mu::Certain(edit),
        }
    }

    /// Create a predicted/uncertain loc_edit (edit wrapped in parentheses)
    /// Used for patterns like c.(9740C>A) where the variant is predicted
    pub fn new_predicted(location: L, edit: E) -> Self {
        Self {
            location,
            edit: Mu::Uncertain(edit),
        }
    }

    pub fn with_uncertainty(location: L, edit: Mu<E>) -> Self {
        Self { location, edit }
    }
}

impl<L: fmt::Display, E: fmt::Display> fmt::Display for LocEdit<L, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.location, self.edit)
    }
}

/// Main HGVS variant enum
///
/// The relationship/separator kind among the sub-descriptions of a single
/// allele bracket. Most variants are true *phase* (cis/trans/mosaic/chimeric),
/// but the enum also carries non-phase relationships expressed with the same
/// `[...]` machinery: `AndOr` (`^`) and `Products` (`,`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AllelePhase {
    /// Same chromosome (cis): [var1;var2]
    Cis,
    /// Different chromosomes (trans): [var1];[var2]
    Trans,
    /// Phase unknown
    Unknown,
    /// Mosaic - variant present in some cells: var1/var2
    /// (somatic variation within an individual)
    Mosaic,
    /// Chimeric - different cell lines: var1//var2
    /// (two distinct cell populations in one individual)
    Chimeric,
    /// And/or - alternatives joined by `^`: var1^var2
    /// ("variant A and/or variant B"; HGVS general.md)
    AndOr,
    /// Products - different transcripts/proteins derived from one allele,
    /// joined by `,`: `r.[a,b]` (HGVS general.md, RNA/splicing.md,
    /// RNA/alleles.md). Not a phase: the members are downstream products of a
    /// single DNA-level event (e.g. alternative splicing), not co-occurrence
    /// relationships. Only meaningful on the r./p. axes.
    Products,
}

impl fmt::Display for AllelePhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AllelePhase::Cis => write!(f, "cis"),
            AllelePhase::Trans => write!(f, "trans"),
            AllelePhase::Unknown => write!(f, "unknown"),
            AllelePhase::Mosaic => write!(f, "mosaic"),
            AllelePhase::Chimeric => write!(f, "chimeric"),
            AllelePhase::AndOr => write!(f, "and/or"),
            AllelePhase::Products => write!(f, "products"),
        }
    }
}

impl AllelePhase {
    /// Returns true if this is a mosaic phase
    pub fn is_mosaic(&self) -> bool {
        matches!(self, AllelePhase::Mosaic)
    }

    /// Returns true if this is a chimeric phase
    pub fn is_chimeric(&self) -> bool {
        matches!(self, AllelePhase::Chimeric)
    }
}

/// Allele variant containing multiple variants
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AlleleVariant {
    /// The variants in this allele
    pub variants: Vec<HgvsVariant>,
    /// Phase relationship
    pub phase: AllelePhase,
    /// Whether the whole allele group is wrapped in an uncertainty
    /// marker `(...)` (predicted). Currently used by the and/or (`^`)
    /// group, e.g. `c.(370A>C^372C>R)`. Defaults to `false`.
    #[serde(default)]
    pub uncertain: bool,
}

/// The anchor positions of `variant`, when it is a genomic insertion whose two
/// positions are **not** a flanking pair; `None` otherwise (#1264).
///
/// `DNA/insertion.md:15` requires an insertion anchor to name *two flanking
/// nucleotides* — "e.g., `123_124`, not `123_125`" — and the parser enforces it
/// on the way in (`validate_no_point_insertion`). A description that violates it
/// is therefore one ferro cannot read back, whoever built it.
///
/// Kept here, beside the type it describes, rather than in the projector that
/// needs it: it is a statement about a variant's well-formedness, and
/// `normalize` consults it too. Putting it in `project` would have made
/// `normalize` depend on `project`, inverting the layering.
///
/// Only a pair of certain, plain endpoints is decidable, matching
/// `validate_no_point_insertion`'s `definitely_not_flanking`: an uncertain
/// boundary or a `(a_b)` range is not something this rule can speak to.
pub(crate) fn non_flanking_genomic_insertion_anchor(variant: &HgvsVariant) -> Option<(u64, u64)> {
    use crate::hgvs::edit::NaEdit;
    use crate::hgvs::uncertainty::Mu;

    let HgvsVariant::Genome(gv) = variant else {
        return None;
    };
    if !matches!(gv.loc_edit.edit.inner(), Some(NaEdit::Insertion { .. })) {
        return None;
    }
    let (Some(Mu::Certain(start)), Some(Mu::Certain(end))) = (
        gv.loc_edit.location.start.as_single(),
        gv.loc_edit.location.end.as_single(),
    ) else {
        return None;
    };
    // A special marker (`pter`/`qter`/`cen`) sets `base` to 0 and names no
    // numeric position, so the pair is not comparable.
    if start.special.is_some() || end.special.is_some() {
        return None;
    }
    // Asked as a subtraction on `end`, not `start.base + 1`: the parser accepts
    // any `u64` position, so a `start` of `u64::MAX` overflows the addition on a
    // pair whose answer is plainly "not flanking". That panics under
    // `debug_assertions` and *wraps* in release, where `[profile.release]` sets
    // no `overflow-checks` — so the panic is not what would surface it in the
    // field. `checked_sub` returns `None` both there and for a reversed pair,
    // and neither is flanking.
    (end.base.checked_sub(start.base) != Some(1)).then_some((start.base, end.base))
}

impl AlleleVariant {
    /// Create a new allele variant
    pub fn new(variants: Vec<HgvsVariant>, phase: AllelePhase) -> Self {
        Self {
            variants,
            phase,
            uncertain: false,
        }
    }

    /// Build an allele, returning `None` when it has no members (#1264).
    ///
    /// An allele with an empty member list has no HGVS rendering: `Display`
    /// emits `[]`, and `parse_hgvs` rejects `[]` — so the value round-trips to
    /// nothing and any consumer chaining a second call fails on it. The parser
    /// already refuses empty brackets everywhere they can appear, which leaves
    /// direct construction as the only way to reach the shape.
    ///
    /// This mirrors [`GenomeRing::new`], which refuses a ring of fewer than two
    /// segments for the same reason ("a 0/1-segment ring would not round-trip").
    ///
    /// [`AlleleVariant::new`] is deliberately left infallible. It is used
    /// throughout the parser and normalizer on member lists that are non-empty
    /// by construction, and changing its signature would churn call sites that
    /// cannot hit this case for no added safety. Prefer `checked` at the
    /// boundaries where the list is assembled from data — a projection, a
    /// filter, an external payload — which is where an empty list can actually
    /// arise.
    pub fn checked(variants: Vec<HgvsVariant>, phase: AllelePhase) -> Option<Self> {
        if variants.is_empty() {
            return None;
        }
        Some(Self::new(variants, phase))
    }

    /// Create a new allele variant wrapped in an uncertainty marker
    /// `(...)` (predicted), e.g. the and/or group `c.(370A>C^372C>R)`.
    pub fn new_uncertain(variants: Vec<HgvsVariant>, phase: AllelePhase) -> Self {
        Self {
            variants,
            phase,
            uncertain: true,
        }
    }

    /// Create a cis allele (same chromosome)
    pub fn cis(variants: Vec<HgvsVariant>) -> Self {
        Self::new(variants, AllelePhase::Cis)
    }

    /// Create a trans allele (different chromosomes)
    pub fn trans(variants: Vec<HgvsVariant>) -> Self {
        Self::new(variants, AllelePhase::Trans)
    }

    /// Create a mosaic (somatic variation, some cells have variant)
    pub fn mosaic(variants: Vec<HgvsVariant>) -> Self {
        Self::new(variants, AllelePhase::Mosaic)
    }

    /// Create a chimeric (two distinct cell populations)
    pub fn chimeric(variants: Vec<HgvsVariant>) -> Self {
        Self::new(variants, AllelePhase::Chimeric)
    }

    /// Create an unknown phase allele
    pub fn unknown_phase(variants: Vec<HgvsVariant>) -> Self {
        Self::new(variants, AllelePhase::Unknown)
    }

    /// Detect whether the allele contains a `del` + `dup` pair over
    /// **overlapping** reference positions, which the HGVS spec disallows:
    /// "descriptions removing part of a reference sequence and replacing it
    /// with part of the same sequence are not allowed" — with the spec's own
    /// example being exactly `NM_004006.2:c.[762_768del;767_774dup]`
    /// (`recommendations/general.md` line 58).
    ///
    /// The trigger is positional **overlap**, not exact cancellation — and
    /// that is deliberate, matching the spec. The spec's example overlaps only
    /// at 767–768 (a 7-base `del` vs an 8-base `dup`) and does *not* exactly
    /// cancel, yet it is disallowed: a `del` combined with a `dup` of
    /// overlapping bases describes removing-then-restoring part of the same
    /// sequence and must be rewritten as a single `delins`. So the check is
    /// intentionally broader than "equal/inverse edits over the same span".
    /// Non-overlapping `del` + `dup` members on the same allele are accepted.
    ///
    /// # This is a scoped spec prohibition, NOT the overlap geometry (#1749)
    ///
    /// It keys on **read** spans, which the rest of the codebase deliberately
    /// does not: `normalize::footprint::WriteFootprint` decides overlap on what
    /// a member *writes*, and by that geometry a `del` and a `dup` whose read
    /// spans intersect are usually disjoint — the `dup` writes at the junction
    /// 3' of its span (`duplication.md:5`), so
    /// `g.[43045721_43045725del;43045723_43045727dup]` denotes one unambiguous
    /// sequence and would be accepted.
    ///
    /// It is refused anyway, and the two are not in conflict because they are
    /// not answering one question. `general.md:58` names this **edit-type
    /// pair** by name and disallows it, and its own worked example
    /// (`NM_004006.2:c.[762_768del;767_774dup]`) overlaps at 767-768 without
    /// cancelling — so the clause keys on read spans by construction and cannot
    /// be derived from a write-footprint geometry. Precedence is spec-explicit
    /// over our judgement, so the clause governs here.
    ///
    /// Two consequences worth keeping in view. This check is the **only**
    /// overlap-adjacent refusal that fires at PARSE, so no error mode opts out
    /// of it — which is one of the cases
    /// `rulings[absolute-prohibition-enforcement-stage]` is about. And its
    /// scope is exactly `del` x `dup`:
    /// widening it to other edit-type pairs would be inventing a rule, while
    /// deriving it from `WriteFootprint` would delete one the spec states.
    ///
    /// Returns `Some((idx_del, idx_dup))` for the first offending pair found
    /// (deterministic by ascending pair index), or `None` otherwise.
    ///
    /// Detection covers any concrete `del` / `dup` pair on a definite
    /// position range on the same accession: bare integer positions,
    /// 5'-UTR (`c.-N`), 3'-UTR (`c.*N`), and intronic offsets
    /// (`c.X+N` / `c.X-N`) on all axes that carry those flags
    /// (`c.`, `n.`, `r.`). Positions are compared on a canonical
    /// `(region, base, offset)` lex-order so cross-region pairs are
    /// disjoint by construction and intronic offsets sort correctly
    /// within their anchor.
    ///
    /// Variants with uncertain boundaries (`?` markers, unbounded
    /// `<pos>?` endpoints) are still skipped — uncertainty makes
    /// overlap undecidable.
    ///
    /// A single accession can host multiple HGVS coordinate axes
    /// (e.g. `NM_*` carries both `c.` and `n.`/`r.`), so the detector
    /// also requires both variants to share an axis before comparing
    /// canonical ranges. A `c.` del and an `n.` dup on the same
    /// accession with the same numeric range are not reported.
    pub fn detect_self_cancelling_pair(variants: &[HgvsVariant]) -> Option<(usize, usize)> {
        // Indexed loops are intentional: we need both `i` and `j` to return
        // the pair indices to the caller.
        #[allow(clippy::needless_range_loop)]
        for i in 0..variants.len() {
            let Some((kind_i, axis_i, range_i, acc_i)) = self_cancelling_descriptor(&variants[i])
            else {
                continue;
            };
            for j in (i + 1)..variants.len() {
                let Some((kind_j, axis_j, range_j, acc_j)) =
                    self_cancelling_descriptor(&variants[j])
                else {
                    continue;
                };
                if acc_i.full() != acc_j.full() {
                    continue;
                }
                // Gate on coordinate-axis identity: a single accession
                // can carry multiple coordinate systems (e.g. NM_*
                // supports both `c.` and `n.`/`r.`), and numerically
                // identical ranges across axes describe disjoint
                // continua. Mixing them would yield false-positive E3006.
                if axis_i != axis_j {
                    continue;
                }
                let (del_idx, dup_idx) = match (kind_i, kind_j) {
                    (SelfCancellingEditKind::Del, SelfCancellingEditKind::Dup) => (i, j),
                    (SelfCancellingEditKind::Dup, SelfCancellingEditKind::Del) => (j, i),
                    _ => continue,
                };
                if ranges_overlap(range_i, range_j) {
                    return Some((del_idx, dup_idx));
                }
            }
        }
        None
    }

    /// Build a new allele after running the spec-mandated self-cancelling
    /// check. Returns `FerroError::Parse` with
    /// `ErrorCode::SelfCancellingAllele` if the allele violates HGVS
    /// `recommendations/general.md` line 58.
    ///
    /// `source_span` is the byte range of the offending allele in the
    /// caller's source string. Pass it through whenever it's known so that
    /// downstream tooling (LSP, structured-error consumers, the web
    /// service) can underline the precise location; pass `None` for
    /// programmatically constructed alleles with no source backing. When
    /// `Some(span)` is provided, the returned error's `pos` is set to
    /// `span.start`.
    pub fn try_new_validated(
        variants: Vec<HgvsVariant>,
        phase: AllelePhase,
        source_span: Option<crate::error::SourceSpan>,
    ) -> Result<Self, crate::error::FerroError> {
        if let Some((dl, du)) = Self::detect_self_cancelling_pair(&variants) {
            return Err(build_self_cancelling_error(dl, du, source_span, None));
        }
        Ok(Self::new(variants, phase))
    }
}

/// Build the E3006 `SelfCancellingAllele` error with the supplied source
/// span. Shared by the parser-side validator and the library-level
/// `AlleleVariant::try_new_validated` so the diagnostic payload stays in
/// lock-step. `source` is the surrounding input string, attached to the
/// `Diagnostic` for caret rendering when available.
pub(crate) fn build_self_cancelling_error(
    del_idx: usize,
    dup_idx: usize,
    source_span: Option<crate::error::SourceSpan>,
    source: Option<&str>,
) -> crate::error::FerroError {
    let pos = source_span.as_ref().map(|s| s.start).unwrap_or(0);
    let mut diagnostic = crate::error::Diagnostic::new()
        .with_code(crate::error::ErrorCode::SelfCancellingAllele)
        .with_hint(
            "HGVS does not allow describing both a deletion and a duplication \
             of overlapping reference positions in the same allele \
             (recommendations/general.md line 58); drop one edit or rewrite \
             as a single delins",
        );
    if let Some(span) = source_span {
        diagnostic = diagnostic.with_span(span);
    }
    if let Some(src) = source {
        diagnostic = diagnostic.with_source(src);
    }
    crate::error::FerroError::Parse {
        pos,
        msg: format!(
            "Self-cancelling allele: variants at index {} (del) and {} (dup) describe \
             overlapping reference positions",
            del_idx, dup_idx
        ),
        diagnostic: Some(Box::new(diagnostic)),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SelfCancellingEditKind {
    Del,
    Dup,
}

/// Coordinate axis of an `HgvsVariant` arm — used by the
/// self-cancelling detector to refuse cross-axis comparisons even when
/// two variants share an accession.
///
/// A single accession can host multiple HGVS coordinate systems
/// (`NM_*` carries `c.` plus `n.`/`r.`; `NC_*` can carry both `g.` and
/// `m.` on the same circular contig in some assemblies), and a numeric
/// range like `100_150` denotes a different stretch of sequence on each
/// axis. Gating on `acc.full()` alone is therefore not enough to
/// suppress false-positive E3006 verdicts; we also require
/// `axis_i == axis_j` before testing range overlap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SelfCancellingAxis {
    Cds,
    Genome,
    Tx,
    Rna,
    Mt,
    Circular,
}

/// Canonical comparable representation of a single position in
/// HGVS-style "region + base + offset" coordinates.
///
/// Lex-ordered as `(region, base, offset)`:
///
/// - `region` is `false` for CDS-proper (`c.123`), 5'UTR (`c.-3`), and
///   any axis without a `*` / `downstream` flag (genome, mito,
///   circular). It is `true` for 3'UTR (`c.*N`, `r.*N`) and tx
///   downstream positions (`n.*N`). Because `false < true`, every
///   CDS-or-5'UTR endpoint sorts before every 3'UTR endpoint, which
///   matches the HGVS coordinate continuum.
/// - `base` carries the signed numeric value as written. 5'UTR
///   positions are negative (`c.-3` → `base = -3`); CDS-proper and
///   3'UTR positions are positive (`c.123` → 123, `c.*5` → 5).
/// - `offset` is the intronic offset (`c.100+5` → 5, `c.100-5` → -5),
///   or 0 when not set. Two positions with the same anchor sort by
///   offset.
///
/// The genome/mito axes never carry a region flag and rarely an
/// offset, but we include both for uniformity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct SelfCancellingPoint {
    region: bool,
    base: i64,
    offset: i64,
}

impl SelfCancellingPoint {
    const fn new(region: bool, base: i64, offset: i64) -> Self {
        Self {
            region,
            base,
            offset,
        }
    }
}

type SelfCancellingRange = (SelfCancellingPoint, SelfCancellingPoint);

/// Extract `(edit-kind, axis, [start, end] canonical range, accession)`
/// if the variant is a candidate for self-cancelling-pair detection.
/// Returns `None` for any variant that is not a concrete `del` / `dup`
/// on a definite (non-uncertain) position range.
///
/// The axis is returned alongside the range because two variants on the
/// same accession but different coordinate systems (`c.` vs `n.`, etc.)
/// describe disjoint sequence continua and must not be compared.
fn self_cancelling_descriptor(
    v: &HgvsVariant,
) -> Option<(
    SelfCancellingEditKind,
    SelfCancellingAxis,
    SelfCancellingRange,
    &Accession,
)> {
    use crate::hgvs::edit::NaEdit;
    let (edit, axis, range, accession) = match v {
        HgvsVariant::Cds(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Cds,
            cds_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        HgvsVariant::Genome(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Genome,
            genome_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        HgvsVariant::Tx(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Tx,
            tx_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        HgvsVariant::Rna(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Rna,
            rna_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        HgvsVariant::Mt(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Mt,
            genome_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        HgvsVariant::Circular(inner) => (
            inner.loc_edit.edit.inner()?,
            SelfCancellingAxis::Circular,
            genome_simple_range(&inner.loc_edit.location)?,
            &inner.accession,
        ),
        _ => return None,
    };
    let kind = match edit {
        NaEdit::Deletion { .. } => SelfCancellingEditKind::Del,
        NaEdit::Duplication { .. } => SelfCancellingEditKind::Dup,
        _ => return None,
    };
    Some((kind, axis, range, accession))
}

/// Return `Some(offset)` if `raw` is a concrete intronic offset, or
/// `None` if it is one of the parser's "unknown offset" sentinels
/// (`+?` / `-?`; see
/// `parser::position::OFFSET_UNKNOWN_{POSITIVE,NEGATIVE}`). The
/// self-cancelling detector skips any endpoint with an unknown offset
/// because overlap is undecidable.
///
/// This used to test four names: the parser's pair *and*
/// `location::GENOME_OFFSET_UNKNOWN_{POSITIVE,NEGATIVE}`, which were a
/// separate declaration of the same two values. Those are now aliases of the
/// constants below, so the extra two arms tested the same values twice —
/// every axis stores the one pair the parser produces.
fn certain_offset(raw: Option<i64>) -> Option<i64> {
    use crate::hgvs::parser::position::{OFFSET_UNKNOWN_NEGATIVE, OFFSET_UNKNOWN_POSITIVE};
    match raw {
        None => Some(0),
        Some(OFFSET_UNKNOWN_POSITIVE) | Some(OFFSET_UNKNOWN_NEGATIVE) => None,
        Some(v) => Some(v),
    }
}

fn cds_simple_range(interval: &crate::hgvs::interval::CdsInterval) -> Option<SelfCancellingRange> {
    let s = interval.start.inner()?;
    let e = interval.end.inner()?;
    // `c.?` carries `base == CDS_BASE_UNKNOWN` even inside a `Mu::Certain`
    // wrapper (so `inner()` returns Some). Filter explicitly: overlap on
    // an unknown base is undecidable.
    if s.is_unknown() || e.is_unknown() {
        return None;
    }
    let s_off = certain_offset(s.offset)?;
    let e_off = certain_offset(e.offset)?;
    Some((
        SelfCancellingPoint::new(s.utr3, s.base, s_off),
        SelfCancellingPoint::new(e.utr3, e.base, e_off),
    ))
}

fn genome_simple_range(
    interval: &crate::hgvs::interval::GenomeInterval,
) -> Option<SelfCancellingRange> {
    let s = interval.start.inner()?;
    let e = interval.end.inner()?;
    let s_off = certain_offset(s.offset)?;
    let e_off = certain_offset(e.offset)?;
    Some((
        SelfCancellingPoint::new(false, s.base as i64, s_off),
        SelfCancellingPoint::new(false, e.base as i64, e_off),
    ))
}

fn tx_simple_range(interval: &crate::hgvs::interval::TxInterval) -> Option<SelfCancellingRange> {
    let s = interval.start.inner()?;
    let e = interval.end.inner()?;
    let s_off = certain_offset(s.offset)?;
    let e_off = certain_offset(e.offset)?;
    Some((
        SelfCancellingPoint::new(s.downstream, s.base, s_off),
        SelfCancellingPoint::new(e.downstream, e.base, e_off),
    ))
}

fn rna_simple_range(interval: &crate::hgvs::interval::RnaInterval) -> Option<SelfCancellingRange> {
    let s = interval.start.inner()?;
    let e = interval.end.inner()?;
    let s_off = certain_offset(s.offset)?;
    let e_off = certain_offset(e.offset)?;
    Some((
        SelfCancellingPoint::new(s.utr3, s.base, s_off),
        SelfCancellingPoint::new(e.utr3, e.base, e_off),
    ))
}

/// Total-ordering key for a cis-allele member, used to render bracketed
/// cis-allele members in genomic (coordinate) order regardless of the order
/// they were written (#1098).
///
/// The key is `(accession, start, end, descriptor)`, with `start` and `end`
/// each spelled `(region, base, offset)`:
///
/// - `accession` groups members by molecule first. A bracketed cis allele is
///   normally single-accession, so this is constant in the common case; for a
///   mixed-accession allele it at least keeps members grouped and
///   deterministic.
/// - `(region, base, offset)` is a canonical point in the same "region + base +
///   offset" coordinate the self-cancelling detector uses, so 5'UTR sorts
///   before CDS-proper before 3'UTR and intronic offsets sort within their
///   anchor. Members whose location cannot be resolved to a definite range
///   (uncertain/unknown positions, or a non-positional arm) get a max sentinel
///   so they sort last, still deterministically.
/// - The **end** breaks a tie on the start (#1261). Two members that share a
///   start are the ones whose rendered order was previously decided by the
///   descriptor, which is arbitrary with respect to where they sit: a
///   duplication places its copy at the junction *after* its last base, so
///   `258dup` and `258_259dup` share a start but occupy interbase 258 and 259
///   respectively, and `"258_259dup" < "258dup"` lexically rendered them
///   descending. Ordering by the end puts them in junction order.
///
///   This cannot reorder members whose spans do not overlap: for those, `a < c`
///   implies `b < c` (else the spans meet), so start-order, end-order and
///   junction-order already agree. Overlapping members do not reach the sort at
///   all — `normalize_allele` skips it when an `OverlapConflict` was warned,
///   since reordering is only meaning-preserving for disjoint members.
/// - `descriptor` (the member's rendered HGVS string) is the final tie-break.
///   It makes the order **total**: two members sharing both endpoints still get
///   distinct keys, so the sort result never depends on input order. This is
///   why a total order is used rather than a stable sort keyed on position
///   alone — the latter would leave same-position members in input order, which
///   is the exact order-dependence #1098 is about.
///
/// **This function is the positional part of that key** — everything before the
/// descriptor. `cis_member_order_cmp` adds the descriptor tie-break on top,
/// and only when it is going to decide.
/// **Test-only, and deliberately so.** Nothing ships this form: both sorts run
/// behind a single-accession gate, so the accession component is constant across
/// every comparison they make and `cis_member_order_cmp_within_accession` is what
/// they call. This is retained as the *reference* the shipped comparator is
/// checked against — see
/// `dropping_the_accession_is_the_same_order_within_one_accession` — because a
/// claim that two orders agree needs both orders to exist.
#[cfg(test)]
pub(crate) fn cis_member_order_prefix(
    v: &HgvsVariant,
) -> (SmolStr, SelfCancellingPoint, SelfCancellingPoint, u8) {
    let accession = v.accession().map(Accession::full_smol).unwrap_or_default();
    let (start, end, rank) = cis_member_position_key(v);
    (accession, start, end, rank)
}

/// `cis_member_order_prefix` without the accession.
///
/// Both callers of the order gate on every member sharing one accession before
/// they sort, so within a sort that component is the same value for every key
/// and can decide no comparison — see [`cis_member_order_cmp_within_accession`].
fn cis_member_position_key(v: &HgvsVariant) -> (SelfCancellingPoint, SelfCancellingPoint, u8) {
    // `SelfCancellingPoint` derives `Ord` over `(region, base, offset)` in that
    // field order, which is exactly the comparison this key wants, so the points
    // go in whole rather than flattened into six scalars.
    // Unrelated to the unknown-OFFSET sentinels (`OFFSET_UNKNOWN_{POSITIVE,NEGATIVE}`,
    // re-exported as `GENOME_OFFSET_UNKNOWN_*`): this is a sorts-last key for a point
    // that has no position, not a `+?`/`-?` marker. It happens to reuse `i64::MAX`
    // because that is what "sorts last" spells.
    let sentinel = SelfCancellingPoint::new(true, i64::MAX, i64::MAX);
    let (start, end) = cis_member_range(v).unwrap_or((sentinel, sentinel));
    (start, end, junction_rank(v))
}

/// Compare two cis members by the total order described on
/// `cis_member_order_prefix`.
///
/// Exactly the lexicographic comparison of
/// `(cis_member_order_prefix(v), format!("{v}"))`: a tuple consults its last
/// component only when every earlier one ties, so moving the render into
/// `then_with` cannot change the order. It changes the cost — the descriptor is
/// the whole member rendered, and the sort used to derive it for every member on
/// every comparison, once per pass of the allele fixed-point loop.
#[cfg(test)]
pub(crate) fn cis_member_order_cmp(a: &HgvsVariant, b: &HgvsVariant) -> std::cmp::Ordering {
    cis_member_order_prefix(a)
        .cmp(&cis_member_order_prefix(b))
        .then_with(|| a.to_string().cmp(&b.to_string()))
}

/// `cis_member_order_cmp` for a member list already known to share a single
/// accession.
///
/// **Identical ordering at such a call site, by construction.** The accession is
/// the key's first component, and if every member renders the same accession
/// then that component is equal in every comparison the sort makes, so it can
/// decide none of them; dropping it leaves the remaining components — and the
/// descriptor tie-break — to give exactly the order the full key gives.
///
/// The point is the cost. `sort_cis_members_by_genomic_order` establishes the
/// single-accession precondition and then sorts, so the full key rendered both
/// members' accessions on **every comparison** — `O(n log n)` renders of a value
/// that was constant across the whole sort, once per pass of the allele
/// fixed-point loop. On a 100-member allele that is thousands of renders per
/// normalization; on the two-member alleles the sweep draws it is four.
pub(crate) fn cis_member_order_cmp_within_accession(
    a: &HgvsVariant,
    b: &HgvsVariant,
) -> std::cmp::Ordering {
    cis_member_position_key(a)
        .cmp(&cis_member_position_key(b))
        .then_with(|| a.to_string().cmp(&b.to_string()))
}

/// Where within its own span a member adds sequence: `0` at the span's start,
/// `1` at its end.
///
/// Breaks a tie that `cis_member_order_cmp`'s `end` cannot (#1301). An
/// insertion's span *is* the gap it fills, so `264_265insCA` adds at interbase
/// 264; a duplication places its copy after its last base, so `264_265dup` adds
/// at 265. The two share both endpoints, and without this the order fell to the
/// descriptor tie-break, which sorts `264_265dup` first — the reverse of the
/// order the members apply in, so the pair rendered out of order and their
/// interbase spans read as overlapping.
///
/// Everything that consumes the bases under its span occupies the whole of it
/// and so ranks with the 3' end: a member that adds at a span's start must sort
/// before one that acts across the same span.
///
/// **Every axis**, protein included (#1328). The protein axis reaches this tie
/// for the same two reasons the nucleotide axes do — `cis_member_range` returns
/// a real range for [`HgvsVariant::Protein`], and `sort_cis_members_by_genomic_order`
/// is axis-agnostic — so while this matched only the six nucleotide-bearing
/// arms, every protein member ranked `1` and the tie fell to the descriptor
/// tie-break, which sorts `dup` before `ins` alphabetically:
/// `p.[Gly4_Ala5insSer;Gly4_Ala5dup]` rendered the `dup` first. That is the same
/// defect #1301 fixed for nucleotides, reversed the same way.
///
/// `ProteinEdit::Insertion` is the protein analogue of `NaEdit::Insertion`: its
/// span is the gap it fills, so it adds at the span's start, where a `dup`
/// places its copy after the span's last residue. The two edit enums are
/// matched separately because they are separate types, not because the rule
/// differs.
fn junction_rank(v: &HgvsVariant) -> u8 {
    use crate::hgvs::edit::{NaEdit, ProteinEdit};

    // The protein axis carries its own edit enum, so it cannot share the
    // `NaEdit` match below; the *rule* it applies is identical.
    if let HgvsVariant::Protein(p) = v {
        return u8::from(!matches!(
            p.loc_edit.edit.inner(),
            Some(ProteinEdit::Insertion { .. })
        ));
    }
    let edit = match v {
        HgvsVariant::Genome(x) => x.loc_edit.edit.inner(),
        HgvsVariant::Circular(x) => x.loc_edit.edit.inner(),
        HgvsVariant::Mt(x) => x.loc_edit.edit.inner(),
        HgvsVariant::Cds(x) => x.loc_edit.edit.inner(),
        HgvsVariant::Tx(x) => x.loc_edit.edit.inner(),
        HgvsVariant::Rna(x) => x.loc_edit.edit.inner(),
        _ => None,
    };
    u8::from(!matches!(edit, Some(NaEdit::Insertion { .. })))
}

/// Canonical **start and end** points of a cis-allele member's location, or
/// `None` when the member has no definite positional range (uncertain/unknown
/// positions, or a non-positional arm such as a null/unknown-allele marker).
/// Reuses the per-axis range extractors that back the self-cancelling detector.
///
/// The end is what breaks a start tie in `cis_member_order_cmp`; see that
/// function's docs for why the start alone is not a sufficient discriminator.
fn cis_member_range(v: &HgvsVariant) -> Option<SelfCancellingRange> {
    match v {
        HgvsVariant::Genome(x) => genome_simple_range(&x.loc_edit.location),
        HgvsVariant::Cds(x) => cds_simple_range(&x.loc_edit.location),
        HgvsVariant::Tx(x) => tx_simple_range(&x.loc_edit.location),
        HgvsVariant::Rna(x) => rna_simple_range(&x.loc_edit.location),
        HgvsVariant::Mt(x) => genome_simple_range(&x.loc_edit.location),
        HgvsVariant::Circular(x) => genome_simple_range(&x.loc_edit.location),
        // The protein axis needs the end for the same reason the nucleotide
        // axes do: `p.Ala3dup` and `p.Ala3_Ala4dup` share a start, so without it
        // their order falls to the descriptor tie-break that #1261 is about.
        // A point location carries `end == start`, so this is the start for
        // everything that is not a range; an absent end degrades to the start
        // rather than dropping the member to the sort's max sentinel.
        HgvsVariant::Protein(x) => {
            let point = |p: &crate::hgvs::location::ProtPos| {
                SelfCancellingPoint::new(false, p.number as i64, 0)
            };
            let start = x.loc_edit.location.start.inner().map(point)?;
            let end = x.loc_edit.location.end.inner().map(point).unwrap_or(start);
            Some((start, end))
        }
        _ => None,
    }
}

/// Returns `true` when ranges `a` and `b` overlap.
///
/// **Precondition**: both ranges are in canonical orientation
/// (`a.0 <= a.1`, `b.0 <= b.1`). The preprocessor's W4001 Phase 15a
/// (`correct_swapped_positions`) enforces this for parsed input;
/// programmatically constructed AlleleVariants must satisfy it too or
/// the verdict may be a false negative.
fn ranges_overlap(a: SelfCancellingRange, b: SelfCancellingRange) -> bool {
    let lo = a.0.max(b.0);
    let hi = a.1.min(b.1);
    lo <= hi
}

/// Set the count of a single-count `Repeat` edit on `v` to `new_count`,
/// returning `true` on success. Used to build the sibling alleles of a
/// shared-position repeat trans allele (`p.Ala2[10];[11]`): clone the first
/// variant and swap in each subsequent allele's count. Variants that are
/// not single-count repeats are left unchanged and return `false`.
pub(crate) fn set_repeat_count(
    v: &mut HgvsVariant,
    new_count: crate::hgvs::edit::RepeatCount,
) -> bool {
    fn na(edit: &mut Mu<NaEdit>, c: crate::hgvs::edit::RepeatCount) -> bool {
        match edit {
            Mu::Certain(NaEdit::Repeat {
                count,
                additional_counts,
                trailing,
                ..
            })
            | Mu::Uncertain(NaEdit::Repeat {
                count,
                additional_counts,
                trailing,
                ..
            }) if additional_counts.is_empty() && trailing.is_none() => {
                *count = c;
                true
            }
            _ => false,
        }
    }
    match v {
        HgvsVariant::Genome(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Cds(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Tx(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Rna(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Mt(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Circular(x) => na(&mut x.loc_edit.edit, new_count),
        HgvsVariant::Protein(x) => match &mut x.loc_edit.edit {
            Mu::Certain(ProteinEdit::Repeat { count, .. })
            | Mu::Uncertain(ProteinEdit::Repeat { count, .. }) => {
                *count = new_count;
                true
            }
            _ => false,
        },
        _ => false,
    }
}

/// The count of a single-count `Repeat` edit on `v`, if any. Used by the
/// shared-position repeat trans Display.
fn repeat_count_of(v: &HgvsVariant) -> Option<&crate::hgvs::edit::RepeatCount> {
    fn na(edit: &Mu<NaEdit>) -> Option<&crate::hgvs::edit::RepeatCount> {
        match edit.inner() {
            Some(NaEdit::Repeat {
                count,
                additional_counts,
                trailing,
                ..
            }) if additional_counts.is_empty() && trailing.is_none() => Some(count),
            _ => None,
        }
    }
    match v {
        HgvsVariant::Genome(x) => na(&x.loc_edit.edit),
        HgvsVariant::Cds(x) => na(&x.loc_edit.edit),
        HgvsVariant::Tx(x) => na(&x.loc_edit.edit),
        HgvsVariant::Rna(x) => na(&x.loc_edit.edit),
        HgvsVariant::Mt(x) => na(&x.loc_edit.edit),
        HgvsVariant::Circular(x) => na(&x.loc_edit.edit),
        HgvsVariant::Protein(x) => match x.loc_edit.edit.inner() {
            Some(ProteinEdit::Repeat { count, .. }) => Some(count),
            _ => None,
        },
        _ => None,
    }
}

/// True iff `variants` is a shared-position repeat trans allele: 2+ members
/// that are single-count repeats sharing accession, coord type, position,
/// and repeat unit — differing only in count. Such an allele renders in the
/// compact `<pos><unit>[c1];[c2]` form (HGVS repeated.md) rather than the
/// generic `[m1];[m2]`.
fn is_shared_repeat_trans(variants: &[HgvsVariant]) -> bool {
    if variants.len() < 2 || !HgvsVariant::all_share_accession_and_type(variants) {
        return false;
    }
    // The compact `<pos><unit>[c1];[c2]` form is the spec canonical for RNA
    // and protein (`recommendations/{protein,DNA}/repeated.md`); the DNA
    // axes (g./c./m./o.) spell each allele out in full (`[member];[member]`,
    // DNA/repeated.md:33). Gate the compact rendering to RNA + protein so
    // DNA repeat trans alleles keep their explicit spec form.
    if !variants
        .iter()
        .all(|v| matches!(v, HgvsVariant::Rna(_) | HgvsVariant::Protein(_)))
    {
        return false;
    }
    // Key = the full Display with the count normalized out; equal keys mean
    // the members differ only in their repeat count.
    let key = |v: &HgvsVariant| -> Option<String> {
        let mut probe = v.clone();
        set_repeat_count(&mut probe, crate::hgvs::edit::RepeatCount::Exact(0))
            .then(|| format!("{}", probe))
    };
    match key(&variants[0]) {
        Some(first) => variants
            .iter()
            .all(|v| key(v).as_deref() == Some(first.as_str())),
        None => false,
    }
}

/// Write the `ACC:<type>.` prefix for compact allele form.
///
/// Per HGVS spec, bracketed `?` is only valid as a whole-allele marker (`[?]`),
/// never mixed with concrete edits inside the same bracket. Compact form is
/// suppressed when any sub-variant carries the per-variant `?` (e.g. `c.?`).
fn use_compact_form(variants: &[HgvsVariant]) -> bool {
    !variants.is_empty()
        && HgvsVariant::all_share_accession_and_type(variants)
        && !variants.iter().any(HgvsVariant::is_loc_edit_unknown)
}

/// For a `Trans` allele, return the first concrete leaf sub-variant if the
/// compact form `ACC:c.[..];[..]` applies. Every concrete leaf — descending
/// one level into nested cis-group members — must share accession and coord
/// type; there must be at least one; and none may carry the per-variant
/// unknown form. `[0]`/`[?]` members contribute no leaves and are permitted
/// alongside concrete members (this is what keeps `ACC:c.[X];[?]` / `;[0]` in
/// compact form).
///
/// The leaves must also agree on their gene-symbol selector — but only when
/// that selector is actually displayed, which is exactly what
/// [`gene_selector_visible`] answers: a **transcript** reference (#1051), a
/// compound `genomic(transcript)` reference (#1139), and the `p.` axis on any
/// accession (#310/#1142) all suppress it. A differing but invisible selector
/// must not block compaction; enforcing it there made Display non-idempotent
/// (#1058).
fn trans_compact_anchor(variants: &[HgvsVariant]) -> Option<&HgvsVariant> {
    let mut anchor: Option<&HgvsVariant> = None;
    for member in variants {
        let leaves: &[HgvsVariant] = match member {
            HgvsVariant::NullAllele | HgvsVariant::UnknownAllele => &[],
            HgvsVariant::Allele(a) => &a.variants,
            other => std::slice::from_ref(other),
        };
        for leaf in leaves {
            if leaf.accession().is_none()
                || matches!(
                    leaf.variant_type(),
                    "allele" | "null" | "unknown" | "r::r" | "g::g"
                )
                || leaf.is_loc_edit_unknown()
            {
                return None;
            }
            match anchor {
                None => anchor = Some(leaf),
                Some(a) => {
                    if leaf.accession() != a.accession() || leaf.variant_type() != a.variant_type()
                    {
                        return None;
                    }
                    // Accessions are equal here, so testing either is
                    // equivalent. Only enforce gene-symbol agreement when the
                    // selector is displayed — `gene_selector_visible` owns that
                    // rule — because blocking compaction on an invisible
                    // mismatch breaks Display idempotency (#1058).
                    let selector_visible = a
                        .accession()
                        .is_some_and(|acc| gene_selector_visible(acc, a.variant_type()));
                    if selector_visible && leaf.gene_symbol() != a.gene_symbol() {
                        return None;
                    }
                }
            }
        }
    }
    anchor
}

/// Write one trans member wrapped in its bracket(s). A cis-group / leaf /
/// `[0]` / `[?]` member renders as `[<inner>]`. An unknown-phase sub-allele
/// member (the trans+mosaic mix `[B](;)C`) brackets only its first member and
/// appends the rest with `(;)` outside the bracket.
fn write_trans_member_bracketed(f: &mut fmt::Formatter<'_>, member: &HgvsVariant) -> fmt::Result {
    if let HgvsVariant::Allele(a) = member {
        if a.phase == AllelePhase::Unknown {
            for (i, sub) in a.variants.iter().enumerate() {
                if i == 0 {
                    write!(f, "[")?;
                    sub.fmt_loc_edit(f)?;
                    write!(f, "]")?;
                } else {
                    write!(f, "(;)")?;
                    sub.fmt_loc_edit(f)?;
                }
            }
            return Ok(());
        }
    }
    write!(f, "[")?;
    write_trans_member(f, member)?;
    write!(f, "]")
}

/// Write the bracket-inner content of one `Trans` allele member (without the
/// surrounding `[` `]`). A nested cis-group member renders its sub-variants'
/// loc-edits joined by `;`; `[0]`/`[?]` render their marker; a leaf renders
/// its loc-edit.
fn write_trans_member(f: &mut fmt::Formatter<'_>, member: &HgvsVariant) -> fmt::Result {
    match member {
        HgvsVariant::NullAllele => write!(f, "0"),
        HgvsVariant::UnknownAllele => write!(f, "?"),
        HgvsVariant::Allele(a) => {
            for (i, sub) in a.variants.iter().enumerate() {
                if i > 0 {
                    write!(f, ";")?;
                }
                sub.fmt_loc_edit(f)?;
            }
            Ok(())
        }
        other => other.fmt_loc_edit(f),
    }
}

/// The first leaf (non-allele) sub-variant that carries an accession,
/// descending through nested allele members. Used to derive the shared
/// accession + coord-type prefix of an and/or-of-alleles or to inherit it
/// onto bare bracketed operands.
pub(crate) fn first_leaf_with_accession(v: &HgvsVariant) -> Option<&HgvsVariant> {
    match v {
        HgvsVariant::Allele(a) => a.variants.iter().find_map(first_leaf_with_accession),
        HgvsVariant::NullAllele | HgvsVariant::UnknownAllele | HgvsVariant::RnaFusion(_) => None,
        other => {
            if other.accession().is_some() {
                Some(other)
            } else {
                None
            }
        }
    }
}

/// True iff every operand of an and/or allele is itself an `Allele` and all
/// their leaves share accession + coord type — the `ACC:p.[..]^[..]` form
/// where the shared prefix is written once.
fn andor_alleles_share_accession(variants: &[HgvsVariant]) -> bool {
    let mut anchor: Option<&HgvsVariant> = None;
    for member in variants {
        let HgvsVariant::Allele(_) = member else {
            return false;
        };
        let leaf = match first_leaf_with_accession(member) {
            Some(l) => l,
            None => return false,
        };
        match anchor {
            None => anchor = Some(leaf),
            Some(a) => {
                if leaf.accession() != a.accession() || leaf.variant_type() != a.variant_type() {
                    return false;
                }
            }
        }
    }
    anchor.is_some()
}

/// Write the bracket-inner content of one and/or allele operand: each
/// member's loc-edit, separated only between adjacent members — a
/// one-member allele emits only that member's loc-edit with no separator.
/// The separator is `(;)` for an unknown-phase group or `;` for cis.
fn write_andor_allele_inner(f: &mut fmt::Formatter<'_>, allele: &AlleleVariant) -> fmt::Result {
    let sep = if allele.phase == AllelePhase::Unknown {
        "(;)"
    } else {
        ";"
    };
    for (i, member) in allele.variants.iter().enumerate() {
        if i > 0 {
            write!(f, "{}", sep)?;
        }
        member.fmt_loc_edit(f)?;
    }
    Ok(())
}

fn write_compact_prefix(f: &mut fmt::Formatter<'_>, first: &HgvsVariant) -> fmt::Result {
    let accession = first
        .accession()
        .expect("compact form requires an accession; guarded by all_share_accession_and_type");
    write!(f, "{}", accession)?;
    if let Some(gene) = first.gene_symbol() {
        // `gene_selector_visible` owns the rule (#1051/#1139 accession-level,
        // #310/#1142 protein-axis). Without the `p.` half a protein *allele*
        // emitted a selector its single-variant sibling has always dropped,
        // because `ProteinVariant`'s own Display never reaches this function.
        if gene_selector_visible(accession, first.variant_type()) {
            write!(f, "({})", gene)?;
        }
    }
    write!(f, ":{}.", first.variant_type())
}

/// True when a gene-symbol selector set on a variant of `variant_type` with
/// `accession` is actually rendered by `Display`.
///
/// This is the **single** answer to "is the selector visible?", and every site
/// that needs it — the compact-prefix writer and both allele-compaction gates —
/// must use it. Two independent rules compose here:
///
/// - the accession-level [`Accession::admits_gene_selector`] (a transcript
///   reference, #1051; a compound reference whose one specification is already
///   spent, #1139);
/// - the coordinate-level `p.` rule: the protein axis takes no gene-symbol
///   selector on **any** accession (#310/#1142), keyed on the rendered type
///   rather than the accession prefix so it covers
///   `NP`/`XP`/`YP`/`ENSP`/`LRG_<n>p<m>`/UniProt and unclassifiable protein
///   references alike.
///
/// Keeping the two rules in one place is what the compaction gates need. A gate
/// that enforces gene agreement on a selector Display does not emit makes
/// `Display` non-idempotent: the expanded form re-parses to all-`None` genes and
/// then compacts (#1058). That bit both the compound case (#1139) and the
/// protein-allele case — `[NP_…(GENE1):p.(…);NP_…(GENE2):p.(…)]` rendered
/// expanded but re-parsed and compacted — when the rules lived apart.
fn gene_selector_visible(accession: &Accession, variant_type: &str) -> bool {
    accession.admits_gene_selector() && variant_type != "p"
}

/// Write `accession(gene):` when a gene-symbol selector is set *and* the
/// reference admits one, otherwise the bare `accession:`.
///
/// Per HGVS Nomenclature (`refseq.md`), the gene-symbol selector is a
/// specification whose accepted values are transcript/protein accessions, not
/// gene symbols; a **transcript** reference is fully specified on its own and
/// takes no selector at all, and no reference admits more than one
/// specification. Which references admit the selector is decided by
/// [`Accession::admits_gene_selector`] — it drops the symbol on a transcript
/// reference (#1051, mirroring the earlier `p.` drop of #310) and on a compound
/// `genomic(transcript)` reference whose one specification is already spent
/// (#1139), and preserves it everywhere else. The value always remains on the
/// struct for programmatic access (`variant.<X>.gene_symbol`), independent of
/// whether Display emits it.
fn write_accession_with_optional_gene(
    f: &mut fmt::Formatter<'_>,
    accession: &Accession,
    gene_symbol: Option<&str>,
) -> fmt::Result {
    write!(f, "{}", accession)?;
    if let Some(gene) = gene_symbol {
        if accession.admits_gene_selector() {
            write!(f, "({})", gene)?;
        }
    }
    Ok(())
}

/// Format the position+edit portion of a genome loc-edit (without the
/// `accession:g.` prefix). Shared by [`GenomeVariant::fmt_loc_edit`] and
/// [`GenomeRing`]'s `Display` so a ring segment round-trips byte-identically
/// to a standalone genome variant.
///
/// Whole-entity identity (`g.=`) / unknown (`g.?`) and a positionless
/// breakpoint insertion (composite SV `[...;insG]`) skip the position; the
/// predicted form wraps position+edit in parens (#241); otherwise the plain
/// `LocEdit` Display is used.
fn fmt_genome_loc_edit(
    f: &mut fmt::Formatter<'_>,
    loc_edit: &LocEdit<GenomeInterval, NaEdit>,
) -> fmt::Result {
    // For whole-entity identity (g.=) or unknown (g.?), or a positionless
    // breakpoint insertion (composite SV `[...;insG]`), skip the position.
    if let Some(edit) = loc_edit.edit.inner() {
        if edit.is_whole_entity() || edit.is_positionless() {
            return write!(f, "{}", loc_edit.edit);
        }
    }
    // Predicted form: wrap position+edit in parens. #241.
    if loc_edit.edit.is_uncertain() {
        if let Some(edit) = loc_edit.edit.inner() {
            return write!(f, "({}{})", loc_edit.location, edit);
        }
    }
    write!(f, "{}", loc_edit)
}

/// True iff `variant` carries a position-bound (not whole-entity)
/// identity edit (`<pos>=` or `<pos><ref>=`). This is the LHS shape
/// of the HGVS spec compact mosaic / chimeric form.
fn is_position_identity_lhs(variant: &HgvsVariant) -> bool {
    let edit_is_pos_identity = |edit: &Mu<NaEdit>| {
        matches!(
            edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        )
    };
    match variant {
        HgvsVariant::Genome(v) => edit_is_pos_identity(&v.loc_edit.edit),
        HgvsVariant::Cds(v) => edit_is_pos_identity(&v.loc_edit.edit),
        HgvsVariant::Tx(v) => edit_is_pos_identity(&v.loc_edit.edit),
        HgvsVariant::Rna(v) => edit_is_pos_identity(&v.loc_edit.edit),
        HgvsVariant::Mt(v) => edit_is_pos_identity(&v.loc_edit.edit),
        HgvsVariant::Circular(v) => edit_is_pos_identity(&v.loc_edit.edit),
        // Protein position-bound identity (`p.Trp24=`) — the LHS of the
        // protein `=/` compact mosaic form.
        HgvsVariant::Protein(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(crate::hgvs::edit::ProteinEdit::Identity {
                whole_protein: false,
                ..
            })
        ),
        _ => false,
    }
}

/// True iff `variant` carries a whole-entity identity edit (the
/// canonical shape produced by `create_identity_variant_from`, used
/// in the `var/=` shorthand). On Display this should render as bare
/// `=` rather than the full synthetic-position form.
fn is_whole_entity_identity_rhs(variant: &HgvsVariant) -> bool {
    let edit_is_whole = |edit: &Mu<NaEdit>| {
        matches!(
            edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: true,
                ..
            })
        )
    };
    match variant {
        HgvsVariant::Genome(v) => edit_is_whole(&v.loc_edit.edit),
        HgvsVariant::Cds(v) => edit_is_whole(&v.loc_edit.edit),
        HgvsVariant::Tx(v) => edit_is_whole(&v.loc_edit.edit),
        HgvsVariant::Rna(v) => edit_is_whole(&v.loc_edit.edit),
        HgvsVariant::Mt(v) => edit_is_whole(&v.loc_edit.edit),
        HgvsVariant::Circular(v) => edit_is_whole(&v.loc_edit.edit),
        _ => false,
    }
}

/// True iff `variant` is a whole-entity NA identity (`r.=`, `c.=`, …) — the LHS
/// shape of a whole-entity-reference mosaic (`r.=/6_8del`). Same predicate as
/// [`is_whole_entity_identity_rhs`]; named for its role as the mosaic LHS.
fn is_whole_entity_identity_lhs(variant: &HgvsVariant) -> bool {
    is_whole_entity_identity_rhs(variant)
}

/// True iff `a` and `b` carry the same coord-system arm AND their
/// `loc_edit.location` values compare equal. Used to decide whether
/// the spec compact mosaic Display form applies to a 2-variant Allele.
fn intervals_match_for_compact_mosaic(a: &HgvsVariant, b: &HgvsVariant) -> bool {
    match (a, b) {
        (HgvsVariant::Genome(x), HgvsVariant::Genome(y)) => {
            x.loc_edit.location == y.loc_edit.location
        }
        (HgvsVariant::Cds(x), HgvsVariant::Cds(y)) => x.loc_edit.location == y.loc_edit.location,
        (HgvsVariant::Tx(x), HgvsVariant::Tx(y)) => x.loc_edit.location == y.loc_edit.location,
        (HgvsVariant::Rna(x), HgvsVariant::Rna(y)) => x.loc_edit.location == y.loc_edit.location,
        (HgvsVariant::Mt(x), HgvsVariant::Mt(y)) => x.loc_edit.location == y.loc_edit.location,
        (HgvsVariant::Circular(x), HgvsVariant::Circular(y)) => {
            x.loc_edit.location == y.loc_edit.location
        }
        (HgvsVariant::Protein(x), HgvsVariant::Protein(y)) => {
            x.loc_edit.location == y.loc_edit.location
        }
        _ => false,
    }
}

/// How the RHS of a compact mosaic / chimeric form is rendered.
enum CompactMosaicRhs {
    /// Spec compact: RHS inherits accession/type/position from a position-identity LHS; emit its edit alone (`Cys`, `del`, `dup`).
    BareEdit,
    /// Whole-entity-`=` LHS: the RHS carries its own position; emit its position+edit (`6_8del`), no accession/type prefix.
    LocEdit,
    /// `var/=` cleanup: the RHS is a whole-entity identity; emit a bare `=`.
    Identity,
}

/// Classify a 2-member compact mosaic / chimeric form, or `None` when it must
/// fall back to the long-form join.
fn compact_mosaic_rhs_kind(lhs: &HgvsVariant, rhs: &HgvsVariant) -> Option<CompactMosaicRhs> {
    if is_position_identity_lhs(lhs) && intervals_match_for_compact_mosaic(lhs, rhs) {
        Some(CompactMosaicRhs::BareEdit)
    } else if is_whole_entity_identity_lhs(lhs) && !is_whole_entity_identity_rhs(rhs) {
        Some(CompactMosaicRhs::LocEdit)
    } else if !is_position_identity_lhs(lhs) && is_whole_entity_identity_rhs(rhs) {
        Some(CompactMosaicRhs::Identity)
    } else {
        None
    }
}

/// Shared Display path for `Mosaic` (`/`) and `Chimeric` (`//`) phases.
///
/// A 2-member allele is rendered compactly when `compact_mosaic_rhs_kind`
/// classifies it (spec compact `<lhs>=/<rhs-edit>`, whole-entity-`=` LHS
/// `<lhs>=/<rhs-loc-edit>`, or `var/=` cleanup); otherwise it falls back to the
/// long-form per-variant join. When `uncertain` is set (a predicted `(...)`
/// wrapper), the compact body is bracketed after the shared coord-type prefix,
/// e.g. `LRG_199t1:p.(Trp24=/Cys)`.
fn write_mosaic_or_chimeric(
    f: &mut fmt::Formatter<'_>,
    variants: &[HgvsVariant],
    sep: &str,
    uncertain: bool,
) -> fmt::Result {
    if variants.len() == 2 && use_compact_form(variants) {
        let lhs = &variants[0];
        let rhs = &variants[1];

        if let Some(kind) = compact_mosaic_rhs_kind(lhs, rhs) {
            if uncertain {
                // Predicted wrapper: `<prefix>(<lhs-bare><sep><rhs-part>)`, e.g.
                // `LRG_199t1:p.(Trp24=/Cys)` / `LRG_199t1:r.(=/6_8del)`.
                write_compact_prefix(f, lhs)?;
                write!(f, "(")?;
                lhs.fmt_loc_edit(f)?;
                write!(f, "{}", sep)?;
                match kind {
                    CompactMosaicRhs::BareEdit => write_bare_edit(f, rhs)?,
                    CompactMosaicRhs::LocEdit => rhs.fmt_loc_edit(f)?,
                    CompactMosaicRhs::Identity => write!(f, "=")?,
                }
                return write!(f, ")");
            }
            // Non-predicted compact form.
            write!(f, "{}{}", lhs, sep)?;
            return match kind {
                CompactMosaicRhs::BareEdit => write_bare_edit(f, rhs),
                CompactMosaicRhs::LocEdit => rhs.fmt_loc_edit(f),
                CompactMosaicRhs::Identity => write!(f, "="),
            };
        }
    }

    // Long-form join (predicted wrappers only arise for the compact forms above).
    for (i, v) in variants.iter().enumerate() {
        if i > 0 {
            write!(f, "{}", sep)?;
        }
        write!(f, "{}", v)?;
    }
    Ok(())
}

/// Write the `NaEdit` portion of `variant` (no accession, no type
/// prefix, no position). Used by `write_mosaic_or_chimeric` for the
/// spec compact RHS.
///
/// Variants that are not NA-coord arms are written with their full
/// `Display` (callers should not invoke this on those — guarded by
/// `use_compact_form`).
fn write_bare_edit(f: &mut fmt::Formatter<'_>, variant: &HgvsVariant) -> fmt::Result {
    match variant {
        HgvsVariant::Genome(v) => write!(f, "{}", v.loc_edit.edit),
        HgvsVariant::Cds(v) => write!(f, "{}", v.loc_edit.edit),
        HgvsVariant::Tx(v) => write!(f, "{}", v.loc_edit.edit),
        // RNA renders nucleotides in lowercase per the HGVS spec. The bare
        // edit must go through `to_rna_string()` — the plain `NaEdit`
        // `Display` is uppercase and would corrupt the case here.
        HgvsVariant::Rna(v) => match v.loc_edit.edit.inner() {
            Some(edit) => write!(f, "{}", edit.to_rna_string()),
            None => write!(f, "{}", v.loc_edit.edit),
        },
        HgvsVariant::Mt(v) => write!(f, "{}", v.loc_edit.edit),
        HgvsVariant::Circular(v) => write!(f, "{}", v.loc_edit.edit),
        // Protein substitution Display renders just the alternative AA, and
        // del/dup render their keyword — exactly the bare-edit RHS shape.
        HgvsVariant::Protein(v) => write!(f, "{}", v.loc_edit.edit),
        _ => write!(f, "{}", variant),
    }
}

impl AlleleVariant {
    /// The single implementation of allele rendering, parameterized by protein
    /// render style. `Display` delegates with `None`; `to_styled_string`
    /// delegates with `Some(style)` so a caller's amino-acid preferences reach
    /// the members — the members are what carry the amino acids, so rendering
    /// them unstyled silently ignored the request.
    fn fmt_with_style(
        &self,
        f: &mut fmt::Formatter<'_>,
        style: Option<crate::hgvs::location::ProteinRenderStyle>,
    ) -> fmt::Result {
        // Per HGVS spec, `[var]` denotes a multi-variant allele; a singleton
        // is just the inner variant. (Mosaic/chimeric already emit bare via
        // their separator-only loops; this unifies cis/trans/unknown.)
        // A valid predicted cis allele always has ≥2 members — enforced by the
        // ';' guard in `find_predicted_cis_bracket` — so this singleton
        // short-circuit never fires for `[(a;b)]` inputs.  The normalizer
        // also guards `allele.uncertain` before collapsing a cis allele to a
        // singleton, keeping this invariant intact through the normalize path.
        if self.variants.len() == 1 {
            return fmt_member_full(f, &self.variants[0], style);
        }
        match self.phase {
            AllelePhase::Cis => {
                // A predicted/uncertain cis allele wraps the bracket content in
                // `(...)`: `[(a;b)]` (recommendations/uncertain.md).
                let (lp, rp) = if self.uncertain { ("(", ")") } else { ("", "") };
                if use_compact_form(&self.variants) {
                    // Compact form: ACC:g.[edit1;edit2] / ACC:p.[(edit1;edit2)]
                    write_compact_prefix(f, &self.variants[0])?;
                    write!(f, "[{}", lp)?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ";")?;
                        }
                        fmt_member_loc_edit(f, v, style)?;
                    }
                    write!(f, "{}]", rp)
                } else {
                    // Expanded form: [ACC:g.edit1;ACC:g.edit2]
                    write!(f, "[{}", lp)?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ";")?;
                        }
                        fmt_member_full(f, v, style)?;
                    }
                    write!(f, "{}]", rp)
                }
            }
            AllelePhase::Products => {
                // `[a,b]` — different transcripts/proteins from one allele.
                // Mirrors the cis compact/expanded split (members may carry
                // distinct transcript accessions, so do not assume shared),
                // joining with `,`. A predicted group wraps the members in
                // `(...)` inside the bracket: `[(a,b)]`.
                let (lp, rp) = if self.uncertain { ("(", ")") } else { ("", "") };
                if use_compact_form(&self.variants) {
                    write_compact_prefix(f, &self.variants[0])?;
                    write!(f, "[{}", lp)?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ",")?;
                        }
                        fmt_member_loc_edit(f, v, style)?;
                    }
                    write!(f, "{}]", rp)
                } else {
                    write!(f, "[{}", lp)?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ",")?;
                        }
                        fmt_member_full(f, v, style)?;
                    }
                    write!(f, "{}]", rp)
                }
            }
            AllelePhase::Trans => {
                // A trans member that is itself a nested cis group (`[a;b]`)
                // needs dedicated rendering; the existing flat-trans paths
                // (which `fmt_loc_edit` a single leaf per bracket) can't
                // express it. Only take the nested path when a nested member
                // is actually present, so flat trans Display is unchanged.
                let has_nested_group = self
                    .variants
                    .iter()
                    .any(|v| matches!(v, HgvsVariant::Allele(_)));
                if has_nested_group {
                    if let Some(anchor) = trans_compact_anchor(&self.variants) {
                        // Compact: ACC:c.[a;b];[c;d] — prefix once, then each
                        // member's bracket-inner content. An unknown-phase
                        // member renders as `[B](;)C` (mosaic tail outside the
                        // bracket).
                        write_compact_prefix(f, anchor)?;
                        for (i, v) in self.variants.iter().enumerate() {
                            if i > 0 {
                                write!(f, ";")?;
                            }
                            write_trans_member_bracketed(f, v)?;
                        }
                        Ok(())
                    } else {
                        // Mixed-reference nested trans (not a spec target):
                        // expanded, each member rendered in full.
                        for (i, v) in self.variants.iter().enumerate() {
                            if i > 0 {
                                write!(f, ";")?;
                            }
                            write_trans_member_bracketed(f, v)?;
                        }
                        Ok(())
                    }
                } else if is_shared_repeat_trans(&self.variants) {
                    // Shared-position repeat trans: `ACC:p.Ala2[10];[11]` —
                    // the position+unit is written once (first member in
                    // full), then each allele's count `;[cN]`. A shared-repeat
                    // group has no nested-cis members, so it is disjoint from
                    // the `has_nested_group` arm above.
                    write_compact_prefix(f, &self.variants[0])?;
                    fmt_member_loc_edit(f, &self.variants[0], style)?;
                    for v in &self.variants[1..] {
                        write!(f, ";")?;
                        // `repeat_count_of` cannot be `None` here: every member
                        // is a single-count repeat (the same invariant
                        // `is_shared_repeat_trans` keyed on). The `if let`
                        // stays defensive — a missing count would otherwise
                        // emit a malformed bare `;`.
                        debug_assert!(
                            repeat_count_of(v).is_some(),
                            "is_shared_repeat_trans guarantees a single-count repeat per member"
                        );
                        if let Some(count) = repeat_count_of(v) {
                            write!(f, "{}", count)?;
                        }
                    }
                    Ok(())
                } else if use_compact_form(&self.variants) {
                    // Compact form: ACC:g.[edit1];[edit2]
                    write_compact_prefix(f, &self.variants[0])?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ";")?;
                        }
                        write!(f, "[")?;
                        fmt_member_loc_edit(f, v, style)?;
                        write!(f, "]")?;
                    }
                    Ok(())
                } else {
                    // Expanded form: [ACC:g.edit1];[ACC:g.edit2]
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, ";")?;
                        }
                        write!(f, "[{}]", v)?;
                    }
                    Ok(())
                }
            }
            AllelePhase::Unknown => {
                // Unknown-phase compact form has no surrounding brackets, so a
                // singleton would print as `ACC:type.edit` and lose the allele
                // wrapper. Only use compact form when there are 2+ sub-variants.
                if self.variants.len() > 1 && use_compact_form(&self.variants) {
                    // Compact form: ACC:g.edit1(;)edit2
                    write_compact_prefix(f, &self.variants[0])?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "(;)")?;
                        }
                        fmt_member_loc_edit(f, v, style)?;
                    }
                    Ok(())
                } else {
                    // Expanded form: [ACC:g.edit1(;)ACC:g.edit2]
                    write!(f, "[")?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "(;)")?;
                        }
                        fmt_member_full(f, v, style)?;
                    }
                    write!(f, "]")
                }
            }
            AllelePhase::Mosaic => write_mosaic_or_chimeric(f, &self.variants, "/", self.uncertain),
            AllelePhase::Chimeric => {
                write_mosaic_or_chimeric(f, &self.variants, "//", self.uncertain)
            }
            AllelePhase::AndOr => {
                if self.uncertain && use_compact_form(&self.variants) {
                    // Uncertainty-wrapped, shared accession + coord type:
                    // `ACC:c.(edit1^edit2)` — prefix once, then the
                    // `^`-joined bare edits inside the parens.
                    write_compact_prefix(f, &self.variants[0])?;
                    write!(f, "(")?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "^")?;
                        }
                        fmt_member_loc_edit(f, v, style)?;
                    }
                    write!(f, ")")
                } else if self.uncertain {
                    // Uncertainty-wrapped but mixed references: wrap the
                    // full-description join in parens — `(ACC1:c.A^ACC2:c.B)`.
                    write!(f, "(")?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "^")?;
                        }
                        fmt_member_full(f, v, style)?;
                    }
                    write!(f, ")")
                } else if andor_alleles_share_accession(&self.variants) {
                    // And/or between bracketed alleles sharing an accession:
                    // `ACC:p.[a(;)b]^[c]` — prefix once, then each operand as
                    // a bracketed allele.
                    let anchor = first_leaf_with_accession(&self.variants[0])
                        .expect("andor_alleles_share_accession guarantees a leaf");
                    write_compact_prefix(f, anchor)?;
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "^")?;
                        }
                        write!(f, "[")?;
                        if let HgvsVariant::Allele(a) = v {
                            write_andor_allele_inner(f, a)?;
                        } else {
                            unreachable!(
                                "andor_alleles_share_accession guarantees all operands are Alleles"
                            )
                        }
                        write!(f, "]")?;
                    }
                    Ok(())
                } else {
                    // And/or `^` join of full descriptions (possibly across
                    // references): render each in full — `ACC1:c.A^ACC2:c.B`.
                    for (i, v) in self.variants.iter().enumerate() {
                        if i > 0 {
                            write!(f, "^")?;
                        }
                        fmt_member_full(f, v, style)?;
                    }
                    Ok(())
                }
            }
        }
    }
}

impl fmt::Display for AlleleVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_with_style(f, None)
    }
}

/// Render an allele member's position+edit, honouring `style` on the `p.` axis.
fn fmt_member_loc_edit(
    f: &mut fmt::Formatter<'_>,
    v: &HgvsVariant,
    style: Option<crate::hgvs::location::ProteinRenderStyle>,
) -> fmt::Result {
    match (v, style) {
        (HgvsVariant::Protein(p), Some(s)) => p.fmt_loc_edit_styled(f, s),
        _ => v.fmt_loc_edit(f),
    }
}

/// Render a full allele member (accession included), honouring `style` on the
/// `p.` axis and recursing so a nested allele keeps it too.
fn fmt_member_full(
    f: &mut fmt::Formatter<'_>,
    v: &HgvsVariant,
    style: Option<crate::hgvs::location::ProteinRenderStyle>,
) -> fmt::Result {
    match (v, style) {
        (HgvsVariant::Protein(p), Some(s)) => p.fmt_styled(f, s),
        (HgvsVariant::Allele(a), _) => a.fmt_with_style(f, style),
        _ => write!(f, "{}", v),
    }
}

/// The coordinate axis (reference molecule / coordinate system) a variant's
/// positions are expressed in.
///
/// Every HGVS description that has a single, well-defined coordinate system maps
/// to exactly one of these. An allele (`ACC:c.[…]`) maps to the axis shared by
/// all of its members; see [`HgvsVariant::coordinate_axis`], which returns
/// `None` when a description has no single axis (an empty or mixed-axis allele,
/// a bare `[0]`/`[?]` marker, or an RNA-fusion `::` construct joining two
/// different transcripts).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CoordinateAxis {
    /// Genomic DNA (`g.`)
    Genomic,
    /// Coding DNA (`c.`)
    Coding,
    /// Non-coding transcript DNA (`n.`)
    NonCoding,
    /// RNA (`r.`)
    Rna,
    /// Protein (`p.`)
    Protein,
    /// Mitochondrial DNA (`m.`)
    Mitochondrial,
    /// Circular DNA (`o.`)
    Circular,
}

impl CoordinateAxis {
    /// The single-letter HGVS coordinate prefix for this axis
    /// (`g`/`c`/`n`/`r`/`p`/`m`/`o`).
    pub fn code(self) -> &'static str {
        match self {
            CoordinateAxis::Genomic => "g",
            CoordinateAxis::Coding => "c",
            CoordinateAxis::NonCoding => "n",
            CoordinateAxis::Rna => "r",
            CoordinateAxis::Protein => "p",
            CoordinateAxis::Mitochondrial => "m",
            CoordinateAxis::Circular => "o",
        }
    }

    /// Whether this axis addresses a DNA molecule (`g`/`c`/`n`/`m`/`o`).
    ///
    /// This is the single home for the DNA-vs-RNA-vs-protein grouping: it treats
    /// mitochondrial and circular DNA as DNA, unlike the narrow legacy
    /// `is_genomic()` predicate (which is `g.`-only).
    pub fn is_dna(self) -> bool {
        matches!(
            self,
            CoordinateAxis::Genomic
                | CoordinateAxis::Coding
                | CoordinateAxis::NonCoding
                | CoordinateAxis::Mitochondrial
                | CoordinateAxis::Circular
        )
    }

    /// Whether this axis addresses an RNA molecule (`r.`).
    pub fn is_rna(self) -> bool {
        matches!(self, CoordinateAxis::Rna)
    }

    /// Whether this axis addresses a protein (`p.`).
    pub fn is_protein(self) -> bool {
        matches!(self, CoordinateAxis::Protein)
    }
}

/// Represents all types of HGVS variants:
/// - g. (genomic)
/// - c. (coding DNA)
/// - n. (non-coding transcript)
/// - r. (RNA)
/// - p. (protein)
/// - m. (mitochondrial)
/// - o. (circular DNA) - SVD-WG006
/// - RNA fusion (::) - SVD-WG007
/// - Ring chromosome (::) — HGVS DNA/complex.md:127
/// - sup (supernumerary chromosome marker) — HGVS DNA/complex.md:33-34
/// - Allele (compound variants)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HgvsVariant {
    /// Genomic variant (g.)
    Genome(GenomeVariant),
    /// Coding DNA variant (c.)
    Cds(CdsVariant),
    /// Non-coding transcript variant (n.)
    Tx(TxVariant),
    /// RNA variant (r.)
    Rna(RnaVariant),
    /// Protein variant (p.)
    Protein(ProteinVariant),
    /// Mitochondrial variant (m.)
    Mt(MtVariant),
    /// Circular DNA variant (o.) - SVD-WG006
    Circular(CircularVariant),
    /// RNA Fusion variant (::) - SVD-WG007
    RnaFusion(RnaFusionVariant),
    /// Ring chromosome: two or more genome edits on a single accession joined
    /// by `::` break junctions (HGVS DNA/complex.md:127/130).
    GenomeRing(GenomeRing),
    /// Supernumerary chromosome marker `sup` (HGVS DNA/complex.md:33-34, the
    /// ISCN named extension for a supernumerary chromosome). Wraps the inner
    /// genome description and renders it with a trailing `sup`.
    ///
    /// Two inner shapes occur in the spec:
    /// - a supernumerary whole chromosome (`pter_qtersup`,
    ///   DNA/duplication.md:117), where the inner is a [`HgvsVariant::Genome`]
    ///   with a `pter_qter` interval and no edit; and
    /// - a supernumerary ring chromosome (`[<ring>]sup`,
    ///   DNA/complex.md:161), where the inner is a [`HgvsVariant::GenomeRing`].
    ///   Unlike a standalone ring (which renders without brackets), the
    ///   supernumerary ring is bracketed (`g.[<ring>]sup`) so the marker
    ///   applies to the whole ring; `Display` adds the brackets for this case.
    Supernumerary(Box<HgvsVariant>),
    /// Allele/compound variant
    Allele(AlleleVariant),
    /// Null allele marker [0] - indicates no variant on this chromosome (hemizygous)
    NullAllele,
    /// Unknown allele marker [?] - indicates unknown variant on second chromosome
    UnknownAllele,
}

impl HgvsVariant {
    /// Get the accession for this variant, if available.
    ///
    /// For allele variants, returns the accession of the first variant.
    /// For RNA fusion variants, returns the 5' partner accession.
    /// Returns `None` for NullAllele, UnknownAllele, or empty allele variants.
    pub fn accession(&self) -> Option<&Accession> {
        match self {
            HgvsVariant::Genome(v) => Some(&v.accession),
            HgvsVariant::Cds(v) => Some(&v.accession),
            HgvsVariant::Tx(v) => Some(&v.accession),
            HgvsVariant::Rna(v) => Some(&v.accession),
            HgvsVariant::Protein(v) => Some(&v.accession),
            HgvsVariant::Mt(v) => Some(&v.accession),
            HgvsVariant::Circular(v) => Some(&v.accession),
            HgvsVariant::RnaFusion(v) => Some(&v.five_prime.accession),
            HgvsVariant::GenomeRing(g) => Some(&g.accession),
            HgvsVariant::Supernumerary(inner) => inner.accession(),
            HgvsVariant::Allele(a) => a.variants.first().and_then(|v| v.accession()),
            HgvsVariant::NullAllele | HgvsVariant::UnknownAllele => None,
        }
    }

    /// Get the [`CoordinateAxis`] (reference molecule / coordinate system) this
    /// variant's positions are expressed in, if it has a single well-defined one.
    ///
    /// For a leaf variant this is simply its coordinate kind. For an allele
    /// (`ACC:c.[…]`) it is the axis shared by every member — HGVS alleles are
    /// single-coordinate-system by construction, so this is normally
    /// well-defined; the method recurses into nested (and/or) sub-alleles and
    /// skips bare `[0]`/`[?]` markers, which carry no axis of their own.
    ///
    /// Returns `None` when there is no single axis:
    /// - an empty allele, or a (programmatically constructed) allele whose
    ///   members disagree on axis;
    /// - a bare `[0]` / `[?]` allele marker; or
    /// - an RNA-fusion `::` construct, which joins two different transcripts
    ///   rather than expressing one coordinate system.
    ///
    /// A genome ring (`ACC:g.[seg1::seg2]`), by contrast, is a single genomic
    /// accession whose `::` are intra-molecule ISCN2020 break junctions, so it
    /// resolves to [`CoordinateAxis::Genomic`].
    pub fn coordinate_axis(&self) -> Option<CoordinateAxis> {
        match self {
            HgvsVariant::Genome(_) => Some(CoordinateAxis::Genomic),
            HgvsVariant::Cds(_) => Some(CoordinateAxis::Coding),
            HgvsVariant::Tx(_) => Some(CoordinateAxis::NonCoding),
            HgvsVariant::Rna(_) => Some(CoordinateAxis::Rna),
            HgvsVariant::Protein(_) => Some(CoordinateAxis::Protein),
            HgvsVariant::Mt(_) => Some(CoordinateAxis::Mitochondrial),
            HgvsVariant::Circular(_) => Some(CoordinateAxis::Circular),
            HgvsVariant::Supernumerary(inner) => inner.coordinate_axis(),
            HgvsVariant::Allele(a) => {
                let mut axis: Option<CoordinateAxis> = None;
                for member in &a.variants {
                    match member.coordinate_axis() {
                        // `[0]`/`[?]` markers carry no axis; skip them so a
                        // `c.[X];[?]`-style allele still resolves to `X`'s axis.
                        // Any other axis-less member (e.g. a nested fusion) makes
                        // the whole allele's axis undefined.
                        None => {
                            if matches!(
                                member,
                                HgvsVariant::NullAllele | HgvsVariant::UnknownAllele
                            ) {
                                continue;
                            }
                            return None;
                        }
                        Some(member_axis) => match axis {
                            None => axis = Some(member_axis),
                            Some(prev) if prev == member_axis => {}
                            Some(_) => return None,
                        },
                    }
                }
                axis
            }
            // A genome ring (`ACC:g.[seg1::seg2]`) is a single genomic accession
            // whose `::` are intra-molecule ISCN2020 break junctions, not a
            // fusion of two frames — every segment is `g.`, so its axis is
            // Genomic. (Cross-chromosome `::` is rejected at parse time.) An
            // RNA fusion, by contrast, joins two *different* transcripts and has
            // no single reference molecule.
            HgvsVariant::GenomeRing(_) => Some(CoordinateAxis::Genomic),
            HgvsVariant::RnaFusion(_) | HgvsVariant::NullAllele | HgvsVariant::UnknownAllele => {
                None
            }
        }
    }

    /// Get the gene-symbol selector for this variant, if one was present in the
    /// original input.
    ///
    /// Mirrors `accession()` and is used by `Display` to preserve the selector
    /// on round-trip (#121). Returns `None` for variant kinds that do not carry
    /// a single top-level selector (`Allele`, `RnaFusion`, `NullAllele`,
    /// `UnknownAllele`); selectors on those nested kinds are emitted by their
    /// own `Display` impls.
    pub fn gene_symbol(&self) -> Option<&str> {
        match self {
            HgvsVariant::Genome(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Cds(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Tx(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Rna(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Protein(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Mt(v) => v.gene_symbol.as_deref(),
            HgvsVariant::Circular(v) => v.gene_symbol.as_deref(),
            HgvsVariant::GenomeRing(g) => g.gene_symbol.as_deref(),
            HgvsVariant::Supernumerary(inner) => inner.gene_symbol(),
            HgvsVariant::RnaFusion(_)
            | HgvsVariant::Allele(_)
            | HgvsVariant::NullAllele
            | HgvsVariant::UnknownAllele => None,
        }
    }

    /// Get the variant type string
    pub fn variant_type(&self) -> &'static str {
        match self {
            HgvsVariant::Genome(_) => "g",
            HgvsVariant::Cds(_) => "c",
            HgvsVariant::Tx(_) => "n",
            HgvsVariant::Rna(_) => "r",
            HgvsVariant::Protein(_) => "p",
            HgvsVariant::Mt(_) => "m",
            HgvsVariant::Circular(_) => "o",
            HgvsVariant::RnaFusion(_) => "r::r",
            HgvsVariant::GenomeRing(_) => "g::g",
            HgvsVariant::Supernumerary(inner) => inner.variant_type(),
            HgvsVariant::Allele(_) => "allele",
            HgvsVariant::NullAllele => "null",
            HgvsVariant::UnknownAllele => "unknown",
        }
    }

    /// Check if this is an allele (compound) variant
    pub fn is_allele(&self) -> bool {
        matches!(self, HgvsVariant::Allele(_))
    }

    /// Check if this is a null allele marker
    pub fn is_null_allele(&self) -> bool {
        matches!(self, HgvsVariant::NullAllele)
    }

    /// Check if this is an unknown allele marker
    pub fn is_unknown_allele(&self) -> bool {
        matches!(self, HgvsVariant::UnknownAllele)
    }

    /// Render this variant under a protein render `style`. Only `p.` variants
    /// are affected; every other coordinate system renders identically to
    /// [`Display`](Self) (the style has no meaning there).
    ///
    /// Styles a single `HgvsVariant::Protein` **and** an allele of protein
    /// members; every other coordinate system renders identically to `Display`,
    /// since the style has no meaning off the `p.` axis.
    ///
    /// The allele arm is not an edge case. This method used to excuse skipping
    /// it on the grounds that "the projector's `.protein` field is always a
    /// single `HgvsVariant::Protein`, never an allele" — no longer true:
    /// separated residues render as a cis allele (#1095 for changed residues,
    /// #1099 for silent ones), so a `.protein` is routinely bracketed and the
    /// caller's amino-acid preferences were silently dropped for it.
    pub fn to_styled_string(&self, style: crate::hgvs::location::ProteinRenderStyle) -> String {
        struct Styled<'a>(&'a HgvsVariant, crate::hgvs::location::ProteinRenderStyle);
        impl fmt::Display for Styled<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                match self.0 {
                    HgvsVariant::Protein(v) => v.fmt_styled(f, self.1),
                    HgvsVariant::Allele(a) => a.fmt_with_style(f, Some(self.1)),
                    other => write!(f, "{}", other),
                }
            }
        }
        format!("{}", Styled(self, style))
    }

    /// Renderings of this variant, **other than** its canonical [`Display`](Self)
    /// form, that the HGVS spec admits as equally correct.
    ///
    /// Only the stop-codon glyph qualifies. The spec's checklist
    /// (`docs/recommendations/checklist.md`) states *"`Ter` or `*` should be used
    /// to indicate a translation stop codon; the `X` should not be used"* — so
    /// `Ter` and `*` are co-equal spellings and `X` alone is deprecated. The spec
    /// then uses both across its own examples. ferro renders `Ter` by policy
    /// (#1114 made the `*` form parse; #1050 added [`TerStyle`] to render it), so a
    /// description spelling the stop `*` names the same variant in a spelling the
    /// spec sanctions.
    ///
    /// The one-letter amino-acid code is deliberately **excluded**, even though
    /// [`ProteinRenderStyle`] can emit it: it is a separate axis, and a caller
    /// asking "does this string name my variant?" should not be told yes for a
    /// three-letter/one-letter difference it never asked to ignore.
    ///
    /// Empty for every non-protein variant, whose rendering the stop style cannot
    /// affect.
    ///
    /// [`TerStyle`]: crate::hgvs::location::TerStyle
    /// [`ProteinRenderStyle`]: crate::hgvs::location::ProteinRenderStyle
    pub fn spec_equivalent_renderings(&self) -> Vec<String> {
        use crate::hgvs::location::{ProteinRenderStyle, TerStyle};
        let starred = self.to_styled_string(ProteinRenderStyle {
            stop: TerStyle::Star,
            ..Default::default()
        });
        if starred == self.to_string() {
            Vec::new()
        } else {
            vec![starred]
        }
    }

    /// Format just the position+edit portion (without accession and coordinate prefix).
    ///
    /// For `NM_000088.3:c.459A>G`, this writes `459A>G`. Used by `AlleleVariant::Display`
    /// to emit the spec-correct compact form (`ACC:c.[edit1;edit2]`).
    ///
    /// Variant types that have no simple loc/edit form (`Allele`, `RnaFusion`,
    /// `NullAllele`, `UnknownAllele`) fall back to their full `Display` output. Callers
    /// guard against this via `all_share_accession_and_type`, which excludes those
    /// types from the compact branch.
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HgvsVariant::Genome(v) => v.fmt_loc_edit(f),
            HgvsVariant::Cds(v) => v.fmt_loc_edit(f),
            HgvsVariant::Tx(v) => v.fmt_loc_edit(f),
            HgvsVariant::Rna(v) => v.fmt_loc_edit(f),
            HgvsVariant::Protein(v) => v.fmt_loc_edit(f),
            HgvsVariant::Mt(v) => v.fmt_loc_edit(f),
            HgvsVariant::Circular(v) => v.fmt_loc_edit(f),
            // These types have no compact form — fall back to full Display.
            HgvsVariant::RnaFusion(v) => write!(f, "{}", v),
            HgvsVariant::GenomeRing(g) => write!(f, "{}", g),
            HgvsVariant::Supernumerary(_) => write!(f, "{}", self),
            HgvsVariant::Allele(a) => write!(f, "{}", a),
            HgvsVariant::NullAllele => write!(f, "0"),
            HgvsVariant::UnknownAllele => write!(f, "?"),
        }
    }

    /// True if this variant's loc/edit portion is the per-variant unknown form
    /// (`g.?`, `c.?`, `n.?`, `r.?`, `p.?`, `m.?`, `o.?`).
    ///
    /// The HGVS spec uses bracketed `?` only as a whole-allele marker (`[?]`),
    /// never mixed with concrete edits inside the same bracket. Compact form is
    /// suppressed when any sub-variant matches this so the output isn't visually
    /// ambiguous with the spec-sanctioned `[?]` form.
    pub(crate) fn is_loc_edit_unknown(&self) -> bool {
        match self {
            HgvsVariant::Genome(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Cds(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Tx(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Rna(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Mt(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Circular(v) => is_na_edit_unknown(&v.loc_edit.edit),
            HgvsVariant::Protein(v) => match &v.loc_edit.edit {
                Mu::Unknown => true,
                Mu::Certain(e) | Mu::Uncertain(e) => e.is_whole_protein_unknown(),
            },
            HgvsVariant::RnaFusion(_)
            | HgvsVariant::GenomeRing(_)
            | HgvsVariant::Supernumerary(_)
            | HgvsVariant::Allele(_)
            | HgvsVariant::NullAllele
            | HgvsVariant::UnknownAllele => false,
        }
    }

    /// Check if all variants in a slice share the same accession, coordinate type, and
    /// gene-symbol selector. Used to determine whether the compact allele form can be
    /// used without losing information.
    ///
    /// The compact form (`ACC(GENE):c.[edit1;edit2]`) can carry exactly one
    /// `(GENE)` selector on the prefix. Per the #121 round-trip policy
    /// ("preserve when present; do not synthesize"), the compact form is only
    /// safe when every sub-variant agrees on `gene_symbol`: both `Some(g)`
    /// (same `g`) and all-`None` are safe; any disagreement (different `g`,
    /// or `Some` vs `None`) falls back to the expanded form so each
    /// sub-variant emits its own selector via per-variant `Display`.
    ///
    /// This gene agreement is required only when the selector is actually
    /// displayed, which is exactly what [`gene_selector_visible`] answers: a
    /// **transcript** reference (#1051), a compound `genomic(transcript)`
    /// reference (#1139), and the `p.` axis on any accession (#310/#1142) all
    /// suppress it, so a differing (invisible) selector cannot appear in either
    /// form. Blocking compaction on it there made Display non-idempotent (the
    /// expanded form reparses to all-`None` genes and then compacts, #1058).
    pub(crate) fn all_share_accession_and_type(variants: &[HgvsVariant]) -> bool {
        let Some(first) = variants.first() else {
            return true;
        };
        let first_acc = first.accession();
        let first_type = first.variant_type();
        let first_gene = first.gene_symbol();

        // Don't use compact form for types that aren't simple coordinate-based variants,
        // or when the first variant has no accession (e.g. NullAllele, UnknownAllele)
        if first_acc.is_none()
            || matches!(first_type, "allele" | "null" | "unknown" | "r::r" | "g::g")
        {
            return false;
        }

        // Only require matching gene symbols when the selector is displayed;
        // `gene_selector_visible` owns that rule. All members share `first_acc`
        // and `first_type`, so the first variant decides visibility for all.
        let selector_visible = first_acc.is_some_and(|acc| gene_selector_visible(acc, first_type));

        variants[1..].iter().all(|v| {
            v.variant_type() == first_type
                && v.accession() == first_acc
                && (!selector_visible || v.gene_symbol() == first_gene)
        })
    }
}

/// True if a nucleotide-edit `Mu` wrapper is a certain, position-only identity
/// edit (`NaEdit::Identity { sequence: None, whole_entity: false }`) — the
/// editless "position reference" form produced when a genome interval is given
/// with no edit (e.g. `g.pter_qter`). Used by the supernumerary whole-chromosome
/// Display to drop the trailing `=` so `pter_qtersup` round-trips.
///
/// Note: this is stricter than [`is_position_identity_lhs`], which accepts any
/// position-bound identity (`whole_entity: false`) regardless of `sequence`.
/// This predicate additionally requires `sequence: None` (no `<ref>` written),
/// so `g.123A=` satisfies `is_position_identity_lhs` but not this — they are not
/// redundant.
fn is_position_only_identity(edit: &Mu<NaEdit>) -> bool {
    matches!(
        edit,
        Mu::Certain(NaEdit::Identity {
            sequence: None,
            whole_entity: false,
        })
    )
}

/// Wrap a valid supernumerary inner (an editless whole-chromosome genome
/// variant, or a [`GenomeRing`]) in [`HgvsVariant::Supernumerary`]. Returns
/// `None` for any other inner — `sup` only applies to those two shapes
/// (HGVS DNA/complex.md:33-34). This is the single constructor enforcing the
/// supernumerary invariant, mirroring [`GenomeRing::new`].
pub(crate) fn make_supernumerary(inner: HgvsVariant) -> Option<HgvsVariant> {
    let ok = matches!(&inner, HgvsVariant::GenomeRing(_))
        || matches!(&inner, HgvsVariant::Genome(g) if is_position_only_identity(&g.loc_edit.edit));
    ok.then(|| HgvsVariant::Supernumerary(Box::new(inner)))
}

/// True if a nucleotide-edit `Mu` wrapper represents the per-variant unknown form
/// (e.g. `c.?`, `r.?`).
fn is_na_edit_unknown(edit: &Mu<NaEdit>) -> bool {
    match edit {
        Mu::Unknown => true,
        Mu::Certain(e) | Mu::Uncertain(e) => e.is_whole_entity_unknown(),
    }
}

impl fmt::Display for HgvsVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HgvsVariant::Genome(v) => write!(f, "{}", v),
            HgvsVariant::Cds(v) => write!(f, "{}", v),
            HgvsVariant::Tx(v) => write!(f, "{}", v),
            HgvsVariant::Rna(v) => write!(f, "{}", v),
            HgvsVariant::Protein(v) => write!(f, "{}", v),
            HgvsVariant::Mt(v) => write!(f, "{}", v),
            HgvsVariant::Circular(v) => write!(f, "{}", v),
            HgvsVariant::RnaFusion(v) => write!(f, "{}", v),
            HgvsVariant::GenomeRing(g) => write!(f, "{}", g),
            HgvsVariant::Supernumerary(inner) => {
                // A supernumerary ring is bracketed (`g.[<ring>]sup`); a bare
                // supernumerary whole chromosome is not (`g.pter_qtersup`).
                match inner.as_ref() {
                    HgvsVariant::GenomeRing(g) => g.fmt_bracketed(f)?,
                    // A whole-chromosome supernumerary carries a position-only
                    // (editless) interval such as `pter_qter`; the spec form is
                    // `pter_qtersup`, with no trailing identity `=`. Render the
                    // location alone so `sup` attaches directly to it.
                    HgvsVariant::Genome(v) if is_position_only_identity(&v.loc_edit.edit) => {
                        write_accession_with_optional_gene(
                            f,
                            &v.accession,
                            v.gene_symbol.as_deref(),
                        )?;
                        write!(f, ":g.{}", v.loc_edit.location)?;
                    }
                    other => write!(f, "{}", other)?,
                }
                write!(f, "sup")
            }
            HgvsVariant::Allele(a) => write!(f, "{}", a),
            HgvsVariant::NullAllele => write!(f, "0"),
            HgvsVariant::UnknownAllele => write!(f, "?"),
        }
    }
}

/// Genomic variant (g.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GenomeVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<GenomeInterval, NaEdit>,
}

impl GenomeVariant {
    /// Format just the position+edit portion (without `accession:g.` prefix).
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_genome_loc_edit(f, &self.loc_edit)
    }
}

impl fmt::Display for GenomeVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":g.")?;
        self.fmt_loc_edit(f)
    }
}

/// A ring chromosome described as two or more genome edits on a single
/// accession joined by `::` break junctions (HGVS DNA/complex.md:127/130 —
/// the ISCN2020 meaning of `::`). Each segment is a normal genome loc-edit
/// (typically a `del`); `Display` joins them with `::`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GenomeRing {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub segments: Vec<LocEdit<GenomeInterval, NaEdit>>,
}

impl GenomeRing {
    /// Build a ring from its segments. Requires at least two segments joined
    /// by `::` (a ring needs >= 2 break junctions on one accession); returns
    /// `None` otherwise, since a 0/1-segment ring would not round-trip.
    pub fn new(
        accession: Accession,
        gene_symbol: Option<String>,
        segments: Vec<LocEdit<GenomeInterval, NaEdit>>,
    ) -> Option<Self> {
        if segments.len() < 2 {
            return None;
        }
        Some(Self {
            accession,
            gene_symbol,
            segments,
        })
    }

    /// Format the `::`-joined ring segments (without the `accession:g.` prefix
    /// or any surrounding brackets). Shared by [`Display`] and
    /// [`GenomeRing::fmt_bracketed`] so the two renderings stay in lock-step.
    fn fmt_segments(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, segment) in self.segments.iter().enumerate() {
            if i > 0 {
                write!(f, "::")?;
            }
            fmt_genome_loc_edit(f, segment)?;
        }
        Ok(())
    }

    /// Format the ring with its `::`-joined segments wrapped in `[...]`, i.e.
    /// `accession:g.[seg1::seg2…]`. This is the shape used when the ring is the
    /// inner of a supernumerary ring chromosome (`g.[<ring>]sup`,
    /// DNA/complex.md:161). The standalone ring [`Display`] is unbracketed.
    fn fmt_bracketed(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":g.[")?;
        self.fmt_segments(f)?;
        write!(f, "]")
    }
}

impl fmt::Display for GenomeRing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":g.")?;
        self.fmt_segments(f)
    }
}

/// Coding DNA variant (c.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CdsVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<CdsInterval, NaEdit>,
}

impl CdsVariant {
    /// Format just the position+edit portion (without `accession:c.` prefix).
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // For whole-entity identity (c.=) or unknown (c.?), skip the position
        if let Some(edit) = self.loc_edit.edit.inner() {
            if edit.is_whole_entity_identity() || edit.is_whole_entity_unknown() {
                return write!(f, "{}", self.loc_edit.edit);
            }
        }
        // Predicted form: wrap position+edit in parens (mirrors the
        // protein canonical form). #241.
        if self.loc_edit.edit.is_uncertain() {
            if let Some(edit) = self.loc_edit.edit.inner() {
                return write!(f, "({}{})", self.loc_edit.location, edit);
            }
        }
        write!(f, "{}", self.loc_edit)
    }
}

impl fmt::Display for CdsVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":c.")?;
        self.fmt_loc_edit(f)
    }
}

/// Non-coding transcript variant (n.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TxVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<TxInterval, NaEdit>,
}

impl TxVariant {
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // For whole-entity identity / unknown / no-product (n.=, n.?, n.0
        // and their predicted wrappers n.(=), n.(?), n.(0)), skip the
        // position. #288 — mirrors the same short-circuits on g./c./r..
        if let Some(edit) = self.loc_edit.edit.inner() {
            if edit.is_whole_entity_identity()
                || edit.is_whole_entity_unknown()
                || edit.is_no_product()
            {
                return write!(f, "{}", self.loc_edit.edit);
            }
        }
        // Predicted form: wrap position+edit in parens. #241.
        if self.loc_edit.edit.is_uncertain() {
            if let Some(edit) = self.loc_edit.edit.inner() {
                return write!(f, "({}{})", self.loc_edit.location, edit);
            }
        }
        write!(f, "{}", self.loc_edit)
    }
}

impl fmt::Display for TxVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":n.")?;
        self.fmt_loc_edit(f)
    }
}

/// RNA variant (r.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RnaVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<RnaInterval, NaEdit>,
}

impl RnaVariant {
    /// Format just the position+edit portion (without `accession:r.` prefix).
    ///
    /// RNA uses lowercase nucleotides per HGVS spec.
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.loc_edit.edit {
            Mu::Certain(edit) => {
                // For whole-entity patterns (r.=, r.?, r.spl, r.0), skip the position
                if edit.is_whole_entity() {
                    write!(f, "{}", edit.to_rna_string())
                } else {
                    write!(f, "{}{}", self.loc_edit.location, edit.to_rna_string())
                }
            }
            Mu::Uncertain(edit) => {
                // For whole-entity patterns, skip the position
                if edit.is_whole_entity() {
                    write!(f, "({})", edit.to_rna_string())
                } else {
                    // Predicted form wraps position+edit in parens
                    // (mirrors the protein canonical form). #241.
                    write!(f, "({}{})", self.loc_edit.location, edit.to_rna_string())
                }
            }
            Mu::Unknown => write!(f, "?"),
        }
    }
}

impl fmt::Display for RnaVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":r.")?;
        self.fmt_loc_edit(f)
    }
}

/// Protein variant (p.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProteinVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<ProtInterval, ProteinEdit>,
}

impl ProteinVariant {
    /// Render the full `p.` HGVS string under `style`. The default style
    /// reproduces [`Display`](Self) byte-for-byte.
    pub fn to_styled_string(&self, style: crate::hgvs::location::ProteinRenderStyle) -> String {
        struct StyledProtein<'a>(
            &'a ProteinVariant,
            crate::hgvs::location::ProteinRenderStyle,
        );
        impl fmt::Display for StyledProtein<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.0.fmt_styled(f, self.1)
            }
        }
        format!("{}", StyledProtein(self, style))
    }

    /// Styled twin of [`Display`](Self): `accession:p.` prefix + styled loc/edit.
    fn fmt_styled(
        &self,
        f: &mut fmt::Formatter<'_>,
        style: crate::hgvs::location::ProteinRenderStyle,
    ) -> fmt::Result {
        write!(f, "{}:p.", self.accession)?;
        self.fmt_loc_edit_styled(f, style)
    }

    /// The single implementation of the position+edit rendering (whole-protein
    /// short-circuit, predicted parens, default), parameterized by style.
    /// [`fmt_loc_edit`](Self::fmt_loc_edit) delegates here with the default
    /// style. The location reuses the generic `Interval`/`Mu` `Display` via the
    /// `StyledProtPos`/`StyledProteinEdit` newtypes, so no structural logic is
    /// duplicated.
    fn fmt_loc_edit_styled(
        &self,
        f: &mut fmt::Formatter<'_>,
        style: crate::hgvs::location::ProteinRenderStyle,
    ) -> fmt::Result {
        use crate::hgvs::edit::StyledProteinEdit;
        use crate::hgvs::interval::Interval;
        use crate::hgvs::location::StyledProtPos;

        // A styled copy of the location interval that reuses Interval's Display.
        let styled_location = |loc: &crate::hgvs::interval::ProtInterval| Interval {
            start: loc.start.map_ref(|p| StyledProtPos(*p, style)),
            end: loc.end.map_ref(|p| StyledProtPos(*p, style)),
        };
        // A styled copy of the edit that reuses Mu's Display (parens / `?`).
        let styled_edit = self.loc_edit.edit.map_ref(|e| StyledProteinEdit(e, style));

        // Whole-protein identity / no-protein / whole-protein unknown: edit only.
        if let Some(edit) = self.loc_edit.edit.inner() {
            if edit.is_whole_protein_identity()
                || edit.is_no_protein()
                || edit.is_whole_protein_unknown()
            {
                return write!(f, "{}", styled_edit);
            }
        }
        // Predicted (uncertain edit): wrap position+edit in parens.
        if self.loc_edit.edit.is_uncertain() {
            if let Some(edit) = self.loc_edit.edit.inner() {
                return write!(
                    f,
                    "({}{})",
                    styled_location(&self.loc_edit.location),
                    StyledProteinEdit(edit, style)
                );
            }
        }
        write!(
            f,
            "{}{}",
            styled_location(&self.loc_edit.location),
            styled_edit
        )
    }

    /// Format just the position+edit portion (without `accession:p.` prefix).
    /// Delegates to [`fmt_loc_edit_styled`](Self::fmt_loc_edit_styled) with the
    /// default style, so the default (and the compound/allele path that calls
    /// this) renders exactly as before.
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_loc_edit_styled(f, crate::hgvs::location::ProteinRenderStyle::default())
    }
}

impl fmt::Display for ProteinVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Per HGVS syntax.yaml lines 119–128 the protein-variant grammar is
        // `sequence_identifier ":" coordinate_type "." aa_position alternate_base`
        // — no parenthesized selector position. The `accession(selector):c.`
        // form (syntax.yaml line 213) is reserved for genomic-to-transcript
        // projection on c./n., not for p. The struct still stores
        // `gene_symbol` so callers can read it programmatically and so the
        // parser (which is permissive about the legacy `NP_*(GENE):p.`
        // form) can round-trip the value; it is just not emitted here. See
        // #310.
        self.fmt_styled(f, crate::hgvs::location::ProteinRenderStyle::default())
    }
}

/// Mitochondrial variant (m.)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MtVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<GenomeInterval, NaEdit>,
}

impl MtVariant {
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // For whole-entity identity / unknown (m.=, m.? and their
        // predicted wrappers m.(=), m.(?)), skip the position. #288 —
        // mirrors the genome short-circuit. There is no m.0 form
        // (DNA isn't "produced"), so no-product isn't accepted here.
        if let Some(edit) = self.loc_edit.edit.inner() {
            if edit.is_whole_entity_identity() || edit.is_whole_entity_unknown() {
                return write!(f, "{}", self.loc_edit.edit);
            }
        }
        // Predicted form: wrap position+edit in parens. #241.
        if self.loc_edit.edit.is_uncertain() {
            if let Some(edit) = self.loc_edit.edit.inner() {
                return write!(f, "({}{})", self.loc_edit.location, edit);
            }
        }
        write!(f, "{}", self.loc_edit)
    }
}

impl fmt::Display for MtVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":m.")?;
        self.fmt_loc_edit(f)
    }
}

/// Circular DNA variant (o.) - SVD-WG006
///
/// Used for circular DNA sequences like plasmids, bacterial chromosomes,
/// and mitochondrial DNA where variants can span the origin.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CircularVariant {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub loc_edit: LocEdit<GenomeInterval, NaEdit>,
}

impl CircularVariant {
    fn fmt_loc_edit(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // For whole-entity identity / unknown (o.=, o.? and their
        // predicted wrappers o.(=), o.(?)), skip the position. #288 —
        // mirrors the genome short-circuit. There is no o.0 form.
        if let Some(edit) = self.loc_edit.edit.inner() {
            if edit.is_whole_entity_identity() || edit.is_whole_entity_unknown() {
                return write!(f, "{}", self.loc_edit.edit);
            }
        }
        // Predicted form: wrap position+edit in parens. #241.
        if self.loc_edit.edit.is_uncertain() {
            if let Some(edit) = self.loc_edit.edit.inner() {
                return write!(f, "({}{})", self.loc_edit.location, edit);
            }
        }
        write!(f, "{}", self.loc_edit)
    }
}

impl fmt::Display for CircularVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":o.")?;
        self.fmt_loc_edit(f)
    }
}

/// RNA Fusion breakpoint - SVD-WG007
///
/// Represents one side of an RNA fusion with accession, gene symbol, and interval
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RnaFusionBreakpoint {
    pub accession: Accession,
    pub gene_symbol: Option<String>,
    pub interval: RnaInterval,
}

impl fmt::Display for RnaFusionBreakpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Route through the shared helper so a fusion breakpoint on a
        // transcript reference drops the gene-symbol selector like every other
        // `r.` form (#1051).
        write_accession_with_optional_gene(f, &self.accession, self.gene_symbol.as_deref())?;
        write!(f, ":r.{}", self.interval)
    }
}

/// RNA Fusion variant (::) - SVD-WG007
///
/// Represents a fusion transcript where two RNA sequences are joined.
/// Common in cancer genomics (BCR-ABL1, EML4-ALK, etc.)
///
/// Format: `accession:r.interval::accession:r.interval`
/// Example: `NM_152263.2:r.-115_775::NM_002609.3:r.1580_*1924`
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RnaFusionVariant {
    /// 5' partner (upstream)
    pub five_prime: RnaFusionBreakpoint,
    /// 3' partner (downstream)
    pub three_prime: RnaFusionBreakpoint,
}

impl RnaFusionVariant {
    pub fn new(five_prime: RnaFusionBreakpoint, three_prime: RnaFusionBreakpoint) -> Self {
        Self {
            five_prime,
            three_prime,
        }
    }
}

impl fmt::Display for RnaFusionVariant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}::{}", self.five_prime, self.three_prime)
    }
}

/// Check if a variant causes a frameshift (net indel length not divisible by 3).
///
/// Returns false if the indel length is 0 or cannot be determined.
pub fn is_frameshift(variant: &HgvsVariant) -> bool {
    match crate::python_helpers::get_indel_length(variant) {
        Some(len) if len != 0 => len % 3 != 0,
        _ => false,
    }
}

/// Like [`is_frameshift`] but uses a provider so wraparound `m.`/`o.`
/// ranges compute the spec-correct circular indel length via
/// [`crate::python_helpers::get_indel_length_with_provider`].
pub fn is_frameshift_with_provider<P: crate::reference::provider::ReferenceProvider + ?Sized>(
    variant: &HgvsVariant,
    provider: &P,
) -> bool {
    match crate::python_helpers::get_indel_length_with_provider(variant, provider) {
        Some(len) if len != 0 => len % 3 != 0,
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hgvs::edit::Base;
    use crate::hgvs::location::GenomePos;

    /// Build an `n.*<start>_*<end><edit>` description.
    ///
    /// #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. The AST shape is still
    /// reachable — [`TxPos::downstream`](crate::hgvs::location::TxPos::downstream)
    /// is public API — which is why the consumers below still have to classify
    /// it.
    fn tx_downstream_range(accession: &str, start: i64, end: i64, edit: &str) -> HgvsVariant {
        use crate::hgvs::interval::TxInterval;
        use crate::hgvs::location::TxPos;
        let mut variant = crate::hgvs::parser::variant::parse_variant(&format!(
            "{accession}:n.{start}_{end}{edit}"
        ))
        .expect("the template parses");
        let HgvsVariant::Tx(tx) = &mut variant else {
            unreachable!("an `n.` description parses as Tx")
        };
        tx.loc_edit.location = TxInterval::new(TxPos::downstream(start), TxPos::downstream(end));
        variant
    }

    #[test]
    fn test_accession_display() {
        let acc = Accession::new("NM", "000088", Some(3));
        assert_eq!(format!("{}", acc), "NM_000088.3");

        let acc_no_version = Accession::new("NM", "000088", None);
        assert_eq!(format!("{}", acc_no_version), "NM_000088");

        // `Display` ignores every format spec, and always has. Pinned here because
        // rewriting `Display` to write its pieces straight into the formatter
        // *looks* like it drops padding that `write!(f, "{}", self.full())`
        // supported — and the first reading of this change said so. It did not:
        // `write!` renders its argument under the inner `"{}"`, which carries no
        // spec, so neither body ever reached `Formatter::pad`. Verified both ways —
        // these assertions pass against the previous body too. See
        // [`Accession::write_full`].
        //
        // Asserted against the bare form rather than against literals, so the
        // property under test is "the spec changes nothing" rather than "the
        // accession is spelled thus", which the two assertions above already pin.
        let bare = format!("{acc}");
        assert_eq!(
            format!("{acc:>20}"),
            bare,
            "width and alignment are ignored"
        );
        assert_eq!(format!("{acc:*^20}"), bare, "fill is ignored");
        assert_eq!(format!("{acc:.4}"), bare, "precision does not truncate");
        assert_eq!(
            format!("{acc:<8.2}"),
            bare,
            "nor do they combine to any effect"
        );
        // And `Display` still agrees with the allocating twin it shares a writer
        // with, which is the invariant the shared writer exists to hold.
        assert_eq!(bare, acc.full());
    }

    #[test]
    fn test_genome_variant_display() {
        let variant = GenomeVariant {
            accession: Accession::new("NC", "000001", Some(11)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                GenomeInterval::point(GenomePos::new(12345)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        };
        assert_eq!(format!("{}", variant), "NC_000001.11:g.12345A>G");
    }

    #[test]
    fn test_cds_variant_display() {
        use crate::hgvs::location::CdsPos;

        let variant = CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(459)),
                NaEdit::Deletion {
                    sequence: None,
                    length: None,
                },
            ),
        };
        assert_eq!(format!("{}", variant), "NM_000088.3:c.459del");
    }

    #[test]
    fn test_allele_cis_display() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let allele = AlleleVariant::cis(vec![var1, var2]);
        let allele_variant = HgvsVariant::Allele(allele);

        assert_eq!(
            format!("{}", allele_variant),
            "NM_000088.3:c.[100A>G;200C>T]"
        );
    }

    #[test]
    fn test_allele_trans_display() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let allele = AlleleVariant::trans(vec![var1, var2]);
        let allele_variant = HgvsVariant::Allele(allele);

        assert_eq!(
            format!("{}", allele_variant),
            "NM_000088.3:c.[100A>G];[200C>T]"
        );
    }

    #[test]
    fn test_allele_cis_three_variants() {
        use crate::hgvs::location::CdsPos;

        let make_var = |pos, alt| {
            HgvsVariant::Cds(CdsVariant {
                accession: Accession::new("NM", "000088", Some(3)),
                gene_symbol: None,
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(pos)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: alt,
                    },
                ),
            })
        };

        let allele = AlleleVariant::cis(vec![
            make_var(100, Base::G),
            make_var(200, Base::C),
            make_var(300, Base::T),
        ]);

        assert_eq!(
            format!("{}", HgvsVariant::Allele(allele)),
            "NM_000088.3:c.[100A>G;200A>C;300A>T]"
        );
    }

    #[test]
    fn test_allele_trans_three_variants() {
        use crate::hgvs::location::CdsPos;

        let make_var = |pos, alt| {
            HgvsVariant::Cds(CdsVariant {
                accession: Accession::new("NM", "000088", Some(3)),
                gene_symbol: None,
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(pos)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: alt,
                    },
                ),
            })
        };

        let allele = AlleleVariant::trans(vec![
            make_var(100, Base::G),
            make_var(200, Base::C),
            make_var(300, Base::T),
        ]);

        assert_eq!(
            format!("{}", HgvsVariant::Allele(allele)),
            "NM_000088.3:c.[100A>G];[200A>C];[300A>T]"
        );
    }

    #[test]
    fn test_allele_unknown_phase_compact_form() {
        // 2+ unknown-phase variants sharing accession + coordinate type emit the
        // bracket-less compact form `ACC:c.edit1(;)edit2`.
        use crate::hgvs::location::CdsPos;

        let make_var = |pos, alt| {
            HgvsVariant::Cds(CdsVariant {
                accession: Accession::new("NM", "000088", Some(3)),
                gene_symbol: None,
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(pos)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: alt,
                    },
                ),
            })
        };

        let pair =
            AlleleVariant::unknown_phase(vec![make_var(100, Base::G), make_var(200, Base::C)]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(pair)),
            "NM_000088.3:c.100A>G(;)200A>C"
        );

        let triple = AlleleVariant::unknown_phase(vec![
            make_var(100, Base::G),
            make_var(200, Base::C),
            make_var(300, Base::T),
        ]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(triple)),
            "NM_000088.3:c.100A>G(;)200A>C(;)300A>T"
        );
    }

    #[test]
    fn test_allele_mixed_coordinate_types_uses_expanded_form() {
        // Same accession, different coordinate types (c. and n.) → expanded form.
        // `all_share_accession_and_type` requires both fields to match.
        use crate::hgvs::location::{CdsPos, TxPos};

        let coding = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let noncoding = HgvsVariant::Tx(TxVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                TxInterval::point(TxPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let cis = AlleleVariant::cis(vec![coding.clone(), noncoding.clone()]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "[NM_000088.3:c.100A>G;NM_000088.3:n.200C>T]"
        );

        let trans = AlleleVariant::trans(vec![coding, noncoding]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(trans)),
            "[NM_000088.3:c.100A>G];[NM_000088.3:n.200C>T]"
        );
    }

    #[test]
    fn test_allele_singleton_emits_bare_form() {
        use crate::hgvs::location::CdsPos;

        let make_var = || {
            HgvsVariant::Cds(CdsVariant {
                accession: Accession::new("NM", "000088", Some(3)),
                gene_symbol: None,
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(100)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: Base::G,
                    },
                ),
            })
        };
        let bare = "NM_000088.3:c.100A>G";

        for allele in [
            AlleleVariant::cis(vec![make_var()]),
            AlleleVariant::trans(vec![make_var()]),
            AlleleVariant::unknown_phase(vec![make_var()]),
            AlleleVariant::mosaic(vec![make_var()]),
            AlleleVariant::chimeric(vec![make_var()]),
        ] {
            assert_eq!(format!("{}", HgvsVariant::Allele(allele)), bare);
        }
    }

    #[test]
    fn test_allele_mixed_accession_uses_expanded_form() {
        use crate::hgvs::location::CdsPos;

        // Different accessions → expanded form (no compact shorthand)
        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000099", Some(1)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let cis = AlleleVariant::cis(vec![var1.clone(), var2.clone()]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "[NM_000088.3:c.100A>G;NM_000099.1:c.200C>T]"
        );

        let trans = AlleleVariant::trans(vec![var1, var2]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(trans)),
            "[NM_000088.3:c.100A>G];[NM_000099.1:c.200C>T]"
        );
    }

    #[test]
    fn test_allele_with_unknown_sub_variant_uses_expanded_form() {
        // Per HGVS spec, bracketed `?` is reserved for the whole-allele marker (`[?]`).
        // An allele containing a `c.?` sub-variant must NOT collapse to `[?;100A>G]` —
        // that would visually conflict with the spec-sanctioned form.
        use crate::hgvs::location::CdsPos;

        let unknown = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(1)),
                NaEdit::whole_entity_unknown(),
            ),
        });
        let concrete = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });

        let trans = AlleleVariant::trans(vec![concrete, unknown]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(trans)),
            "[NM_000088.3:c.100A>G];[NM_000088.3:c.?]"
        );
    }

    #[test]
    fn test_allele_compact_form_transcript_ref_compacts_despite_gene_mismatch() {
        // Hand-built cis/trans alleles: same transcript accession, same
        // coordinate type, but the sub-variants disagree on gene_symbol. On a
        // transcript reference the gene-symbol selector is never displayed
        // (#1051), so a differing selector cannot appear in either the compact
        // or the expanded form. Blocking compaction on that invisible mismatch
        // (the old behavior) made Display non-idempotent: the expanded form
        // reparses to all-`None` genes and then compacts (#1058). So on a
        // transcript reference the compaction decision must be gene-agnostic.
        use crate::hgvs::location::CdsPos;

        let acc = Accession::new("NM", "000088", Some(3));
        let v_a = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A1".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let v_b = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A2".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let cis = AlleleVariant::cis(vec![v_a.clone(), v_b.clone()]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "NM_000088.3:c.[100A>G;200C>T]",
            "mismatched gene symbols on a transcript reference must not block \
             compaction (the selector is not displayed either way, #1058)"
        );

        let trans = AlleleVariant::trans(vec![v_a, v_b]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(trans)),
            "NM_000088.3:c.[100A>G];[200C>T]",
            "mismatched gene symbols on a transcript reference must not block \
             trans compaction either (#1058)"
        );
    }

    #[test]
    fn test_allele_compact_form_transcript_ref_compacts_gene_some_vs_none() {
        // First sub-variant has Some(gene), second has None. On a transcript
        // reference neither selector is displayed, so this Some/None mismatch
        // is likewise invisible and must not block compaction (#1058).
        use crate::hgvs::location::CdsPos;

        let acc = Accession::new("NM", "000088", Some(3));
        let v_with = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A1".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let v_bare = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let cis = AlleleVariant::cis(vec![v_with, v_bare]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "NM_000088.3:c.[100A>G;200C>T]",
            "Some/None gene_symbol mismatch on a transcript reference must not \
             block compaction (#1058)"
        );
    }

    #[test]
    fn test_allele_compact_form_nontranscript_ref_requires_matching_gene_symbol() {
        // On a *non*-transcript (genomic) reference the gene-symbol selector IS
        // displayed, and a compact prefix carries exactly one selector. A
        // differing selector must still force the expanded form so each
        // sub-variant emits its own selector verbatim (#121 preserve policy) --
        // the #1058 carve-out is transcript-reference-only.
        use crate::hgvs::location::CdsPos;

        // NG_ genomic reference with c. coordinates supplied via genomic context.
        let acc = Accession::new("NG", "007400", Some(1));
        let v_a = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A1".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let v_b = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A2".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let cis = AlleleVariant::cis(vec![v_a, v_b]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "[NG_007400.1(COL1A1):c.100A>G;NG_007400.1(COL1A2):c.200C>T]",
            "mismatched gene symbols on a non-transcript reference must still \
             use the expanded form so both selectors survive"
        );
    }

    #[test]
    fn test_allele_display_idempotent_mismatched_gene_transcript_ref() {
        // #1058 regression: a mismatched-gene cis/trans allele on a transcript
        // reference must survive Display -> parse -> Display unchanged. Before
        // the fix, the first Display emitted the expanded (bracket) form whose
        // selectors are suppressed; reparsing produced all-`None` genes, and
        // the second Display compacted -- a non-idempotent drift.
        use crate::hgvs::location::CdsPos;
        use crate::parse_hgvs;

        let acc = Accession::new("NM", "000088", Some(3));
        let v_a = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A1".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let v_b = HgvsVariant::Cds(CdsVariant {
            accession: acc.clone(),
            gene_symbol: Some("COL1A2".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        for allele in [
            AlleleVariant::cis(vec![v_a.clone(), v_b.clone()]),
            AlleleVariant::trans(vec![v_a.clone(), v_b.clone()]),
        ] {
            let first = format!("{}", HgvsVariant::Allele(allele));
            let reparsed = parse_hgvs(&first).expect("first Display must reparse");
            let second = format!("{}", reparsed);
            assert_eq!(
                first, second,
                "Display -> parse -> Display must be stable for a mismatched-gene \
                 allele on a transcript reference (#1058)"
            );
        }
    }

    #[test]
    fn test_allele_compact_form_keeps_compact_when_all_match() {
        // All sub-variants share Some(same gene): compact form is safe and
        // emits the selector once on the prefix (regression test for the
        // happy path so the new compact-form rule isn't over-constrained).
        use crate::hgvs::location::CdsPos;

        let acc = Accession::new("NM", "000088", Some(3));
        let mk = |pos: i64, alt: Base| {
            HgvsVariant::Cds(CdsVariant {
                accession: acc.clone(),
                gene_symbol: Some("COL1A1".to_string()),
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(pos)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: alt,
                    },
                ),
            })
        };
        let cis = AlleleVariant::cis(vec![mk(100, Base::G), mk(200, Base::T)]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "NM_000088.3:c.[100A>G;200A>T]",
            "matching gene symbols keep compact form; the selector itself is \
             dropped on a transcript reference (#1051)"
        );

        // All-None: existing compact behavior must be preserved.
        let mk_none = |pos: i64, alt: Base| {
            HgvsVariant::Cds(CdsVariant {
                accession: acc.clone(),
                gene_symbol: None,
                loc_edit: LocEdit::new(
                    CdsInterval::point(CdsPos::new(pos)),
                    NaEdit::Substitution {
                        reference: Base::A,
                        alternative: alt,
                    },
                ),
            })
        };
        let cis_none = AlleleVariant::cis(vec![mk_none(100, Base::G), mk_none(200, Base::T)]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis_none)),
            "NM_000088.3:c.[100A>G;200A>T]",
            "all-None gene_symbol must use compact form unchanged"
        );
    }

    #[test]
    fn test_allele_null_variant_singleton_delegates() {
        // NullAllele has no accession; the singleton path must not invoke
        // `use_compact_form` (which would deref the missing accession).
        let null = HgvsVariant::NullAllele;
        let cis = AlleleVariant::cis(vec![null]);
        assert_eq!(format!("{}", HgvsVariant::Allele(cis)), "0");
    }

    #[test]
    fn test_allele_accession() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Deletion {
                    sequence: None,
                    length: None,
                },
            ),
        });

        let allele = AlleleVariant::cis(vec![var1]);
        let allele_variant = HgvsVariant::Allele(allele);

        assert_eq!(
            &*allele_variant
                .accession()
                .expect("Expected accession")
                .prefix,
            "NM"
        );
        assert!(allele_variant.is_allele());
    }

    #[test]
    fn test_allele_mosaic_display() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let allele = AlleleVariant::mosaic(vec![var1, var2]);
        let allele_variant = HgvsVariant::Allele(allele);

        // Mosaic uses single slash separator: var1/var2
        assert_eq!(
            format!("{}", allele_variant),
            "NM_000088.3:c.100A>G/NM_000088.3:c.200C>T"
        );
    }

    #[test]
    fn test_allele_chimeric_display() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let allele = AlleleVariant::chimeric(vec![var1, var2]);
        let allele_variant = HgvsVariant::Allele(allele);

        // Chimerism uses double slash separator: var1//var2
        assert_eq!(
            format!("{}", allele_variant),
            "NM_000088.3:c.100A>G//NM_000088.3:c.200C>T"
        );
    }

    #[test]
    fn test_allele_phase_variants() {
        // Verify all phase types are correctly identified
        assert!(!AllelePhase::Cis.is_mosaic());
        assert!(!AllelePhase::Trans.is_mosaic());
        assert!(!AllelePhase::Unknown.is_mosaic());
        assert!(AllelePhase::Mosaic.is_mosaic());
        assert!(!AllelePhase::Chimeric.is_mosaic());
        assert!(!AllelePhase::AndOr.is_mosaic());
        assert!(!AllelePhase::Products.is_mosaic());

        assert!(!AllelePhase::Cis.is_chimeric());
        assert!(!AllelePhase::Trans.is_chimeric());
        assert!(!AllelePhase::Unknown.is_chimeric());
        assert!(!AllelePhase::Mosaic.is_chimeric());
        assert!(AllelePhase::Chimeric.is_chimeric());
        assert!(!AllelePhase::AndOr.is_chimeric());
        assert!(!AllelePhase::Products.is_chimeric());
    }

    // ============== Accession Tests ==============

    #[test]
    fn test_accession_new() {
        let acc = Accession::new("NM", "000088", Some(3));
        assert_eq!(&*acc.prefix, "NM");
        assert_eq!(&*acc.number, "000088");
        assert_eq!(acc.version, Some(3));
        assert!(!acc.ensembl_style);
    }

    #[test]
    fn test_accession_with_style() {
        let acc = Accession::with_style("ENST", "00000012345", Some(1), true);
        assert!(acc.ensembl_style);
        assert_eq!(format!("{}", acc), "ENST00000012345.1");
    }

    #[test]
    fn test_accession_from_assembly() {
        let acc = Accession::from_assembly("GRCh37", "chr1");
        assert!(acc.is_assembly_ref());
        assert_eq!(format!("{}", acc), "GRCh37(chr1)");
    }

    #[test]
    fn test_accession_is_ensembl_prefix() {
        // Human prefixes (empty species code).
        assert!(Accession::is_ensembl_prefix("ENST"));
        assert!(Accession::is_ensembl_prefix("ENSG"));
        assert!(Accession::is_ensembl_prefix("ENSP"));
        assert!(Accession::is_ensembl_prefix("ENSE"));
        assert!(Accession::is_ensembl_prefix("ENSR"));

        // Non-human species prefixes — same five feature suffixes,
        // species code (`MUS`, `RNO`, `BTA`, `DAR`, `CAF`, `SSC`, …) sits
        // between `ENS` and the suffix.
        assert!(Accession::is_ensembl_prefix("ENSMUST"));
        assert!(Accession::is_ensembl_prefix("ENSMUSG"));
        assert!(Accession::is_ensembl_prefix("ENSMUSP"));
        assert!(Accession::is_ensembl_prefix("ENSMUSE"));
        assert!(Accession::is_ensembl_prefix("ENSMUSR"));
        assert!(Accession::is_ensembl_prefix("ENSRNOT"));
        assert!(Accession::is_ensembl_prefix("ENSBTAG"));
        assert!(Accession::is_ensembl_prefix("ENSDARP"));
        assert!(Accession::is_ensembl_prefix("ENSCAFT"));
        assert!(Accession::is_ensembl_prefix("ENSSSCG"));

        // Negative cases.
        assert!(!Accession::is_ensembl_prefix("NM"));
        assert!(!Accession::is_ensembl_prefix("NC"));
        assert!(!Accession::is_ensembl_prefix("ENS")); // no feature suffix
        assert!(!Accession::is_ensembl_prefix("ENSA")); // suffix not in {G,T,P,E,R}
        assert!(!Accession::is_ensembl_prefix("ENSmust")); // lowercase rejected
        assert!(!Accession::is_ensembl_prefix("ENSMUS1T")); // digit in species code
        assert!(!Accession::is_ensembl_prefix("")); // empty
        assert!(!Accession::is_ensembl_prefix("ANYTHING"));
        // Species-code length is bounded at 5 chars (Ensembl convention).
        assert!(Accession::is_ensembl_prefix("ENSAAAAAT")); // 5-letter species code + feature: accept
        assert!(!Accession::is_ensembl_prefix("ENSAAAAAAT")); // 6-letter species code + feature: reject
        assert!(!Accession::is_ensembl_prefix("ENSAAAAAAAAAT")); // grossly overlong: reject
    }

    #[test]
    fn test_accession_is_ensembl() {
        let ensembl = Accession::new("ENST", "00000012345", Some(1));
        assert!(ensembl.is_ensembl());

        let refseq = Accession::new("NM", "000088", Some(3));
        assert!(!refseq.is_ensembl());
    }

    #[test]
    fn test_accession_validate_ensembl() {
        // Valid Ensembl ID (11 digits)
        let valid = Accession::new("ENST", "00000012345", Some(1));
        assert!(valid.validate_ensembl());

        // Non-Ensembl IDs should always validate
        let refseq = Accession::new("NM", "000088", Some(3));
        assert!(refseq.validate_ensembl());
    }

    #[test]
    fn test_accession_inferred_variant_type() {
        assert_eq!(
            Accession::new("NC", "000001", Some(11)).inferred_variant_type(),
            Some("g")
        );
        assert_eq!(
            Accession::new("NG", "012345", Some(1)).inferred_variant_type(),
            Some("g")
        );
        assert_eq!(
            Accession::new("NM", "000088", Some(3)).inferred_variant_type(),
            Some("c")
        );
        assert_eq!(
            Accession::new("NR", "123456", Some(1)).inferred_variant_type(),
            Some("n")
        );
        assert_eq!(
            Accession::new("NP", "000079", Some(2)).inferred_variant_type(),
            Some("p")
        );
        assert_eq!(
            Accession::new("ENST", "00000012345", Some(1)).inferred_variant_type(),
            Some("c")
        );
        assert_eq!(
            Accession::new("ENSG", "00000012345", Some(1)).inferred_variant_type(),
            Some("g")
        );
        assert_eq!(
            Accession::new("ENSP", "00000012345", Some(1)).inferred_variant_type(),
            Some("p")
        );
        // Species-qualified Ensembl accessions (#1057): the feature suffix
        // (T/G/P) drives the type regardless of the species code (MUS, RNO, …),
        // exactly as it does for the human (empty species code) forms above.
        assert_eq!(
            Accession::new("ENSMUST", "00000012345", Some(1)).inferred_variant_type(),
            Some("c")
        );
        assert_eq!(
            Accession::new("ENSRNOT", "00000012345", Some(1)).inferred_variant_type(),
            Some("c")
        );
        assert_eq!(
            Accession::new("ENSMUSG", "00000012345", Some(1)).inferred_variant_type(),
            Some("g")
        );
        assert_eq!(
            Accession::new("ENSMUSP", "00000012345", Some(1)).inferred_variant_type(),
            Some("p")
        );
        // Ensembl exon (E) and regulatory (R) features have no HGVS coordinate
        // type — they are not variant references — so they infer nothing.
        assert_eq!(
            Accession::new("ENSE", "00000012345", Some(1)).inferred_variant_type(),
            None
        );
        assert_eq!(
            Accession::new("ENSMUSE", "00000012345", Some(1)).inferred_variant_type(),
            None
        );
        // The Compara gene-tree feature `GT` (`ENSGT…`) ends in `T` but is NOT
        // a transcript — it must infer nothing, not `c` (the multi-letter
        // feature must not be classified by its final letter alone).
        assert_eq!(
            Accession::new("ENSGT", "00000012345", Some(1)).inferred_variant_type(),
            None
        );
        assert_eq!(
            Accession::new("LRG", "1", None).inferred_variant_type(),
            Some("g")
        );
        // LRG transcript discriminator (`t<M>`) → coding (c.)
        // The transcript discriminator is captured in `number` (e.g. "1t1"),
        // so the dispatch must inspect it rather than only the prefix.
        // See https://www.lrg-sequence.org/faq/ — `t<N>` is the transcript.
        assert_eq!(
            Accession::new("LRG", "1t1", None).inferred_variant_type(),
            Some("c")
        );
        assert_eq!(
            Accession::new("LRG", "292t1", None).inferred_variant_type(),
            Some("c")
        );
        // LRG protein discriminator (`p<M>`) → protein (p.)
        assert_eq!(
            Accession::new("LRG", "1p1", None).inferred_variant_type(),
            Some("p")
        );
        assert_eq!(
            Accession::new("LRG", "673p1", None).inferred_variant_type(),
            Some("p")
        );
        // UniProt single-letter prefix
        assert_eq!(
            Accession::new("P", "12345", None).inferred_variant_type(),
            Some("p")
        );
        // Unknown prefix
        assert_eq!(
            Accession::new("XX", "12345", None).inferred_variant_type(),
            None
        );
    }

    #[test]
    fn test_accession_is_transcript_reference() {
        // RefSeq transcript families are transcript references.
        assert!(Accession::new("NM", "000088", Some(3)).is_transcript_reference());
        assert!(Accession::new("NR", "046018", Some(2)).is_transcript_reference());
        assert!(Accession::new("XM", "011535467", Some(1)).is_transcript_reference());
        assert!(Accession::new("XR", "001737893", Some(1)).is_transcript_reference());

        // Human Ensembl transcript (empty species code).
        assert!(Accession::new("ENST", "00000012345", Some(1)).is_transcript_reference());
        // Species-qualified Ensembl transcripts must classify the same way
        // (#1057) — the species code (MUS, RNO, BTA, …) is irrelevant.
        assert!(Accession::new("ENSMUST", "00000012345", Some(1)).is_transcript_reference());
        assert!(Accession::new("ENSRNOT", "00000012345", Some(1)).is_transcript_reference());
        assert!(Accession::new("ENSBTAT", "00000012345", Some(1)).is_transcript_reference());

        // LRG transcript form (`t<M>` discriminator captured in `number`).
        assert!(Accession::new("LRG", "199t1", None).is_transcript_reference());

        // Non-transcript references are not.
        assert!(!Accession::new("NC", "000013", Some(11)).is_transcript_reference());
        assert!(!Accession::new("NG", "012345", Some(1)).is_transcript_reference());
        assert!(!Accession::new("NP", "000079", Some(2)).is_transcript_reference());
        // Ensembl gene/protein/exon/regulatory features are not transcripts,
        // for the human forms and their species-qualified counterparts alike.
        assert!(!Accession::new("ENSG", "00000012345", Some(1)).is_transcript_reference());
        assert!(!Accession::new("ENSP", "00000012345", Some(1)).is_transcript_reference());
        assert!(!Accession::new("ENSMUSG", "00000012345", Some(1)).is_transcript_reference());
        assert!(!Accession::new("ENSMUSP", "00000012345", Some(1)).is_transcript_reference());
        assert!(!Accession::new("ENSE", "00000012345", Some(1)).is_transcript_reference());
        // Compara gene tree (`ENSGT…`): its feature `GT` ends in `T` but must
        // not be misread as a transcript reference.
        assert!(!Accession::new("ENSGT", "00000012345", Some(1)).is_transcript_reference());
        assert!(!Accession::is_ensembl_transcript_prefix("ENSGT"));
        // Bare LRG genomic record (no `t<M>`) is not a transcript reference.
        assert!(!Accession::new("LRG", "199", None).is_transcript_reference());
        // Custom / unknown prefixes are not transcript references.
        assert!(!Accession::new("XX", "12345", None).is_transcript_reference());
    }

    #[test]
    fn test_accession_is_uniprot() {
        // Valid UniProt
        let uniprot = Accession::new("P", "12345", None);
        assert!(uniprot.is_uniprot());

        // Not UniProt - prefix too long
        let not_uniprot = Accession::new("NM", "000088", Some(3));
        assert!(!not_uniprot.is_uniprot());

        // Not UniProt - number wrong length
        let wrong_length = Accession::new("P", "123", None);
        assert!(!wrong_length.is_uniprot());
    }

    #[test]
    fn test_accession_is_mitochondrial() {
        // GRCh38 rCRS mitochondrion
        assert!(Accession::new("NC", "012920", Some(1)).is_mitochondrial());

        // Deprecated rCRS draft
        assert!(Accession::new("NC", "001807", Some(1)).is_mitochondrial());

        // Version-agnostic — coercion keys off prefix+number, not version
        assert!(Accession::new("NC", "012920", None).is_mitochondrial());

        // Other NC accessions (e.g. chromosome 1) are not mitochondrial
        assert!(!Accession::new("NC", "000001", Some(11)).is_mitochondrial());

        // Same number, different prefix is not mitochondrial
        assert!(!Accession::new("NM", "012920", Some(1)).is_mitochondrial());
    }

    #[test]
    fn test_accession_is_lrg_prefix() {
        assert!(Accession::is_lrg_prefix("LRG"));
        assert!(!Accession::is_lrg_prefix("lrg"));
        assert!(!Accession::is_lrg_prefix("LRG_"));
        assert!(!Accession::is_lrg_prefix("NM"));
        assert!(!Accession::is_lrg_prefix(""));
    }

    #[test]
    fn test_accession_is_lrg() {
        assert!(Accession::new("LRG", "1", None).is_lrg());
        assert!(Accession::new("LRG", "1t1", None).is_lrg());
        assert!(Accession::new("LRG", "1p1", None).is_lrg());
        assert!(!Accession::new("NM", "000088", Some(3)).is_lrg());
        assert!(!Accession::new("NC", "000001", Some(11)).is_lrg());
    }

    #[test]
    fn test_accession_base() {
        let acc = Accession::new("NM", "000088", Some(3));
        assert_eq!(acc.base(), "NM_000088");

        let ensembl = Accession::with_style("ENST", "00000012345", Some(1), true);
        assert_eq!(ensembl.base(), "ENST00000012345");

        let assembly = Accession::from_assembly("GRCh38", "chrX");
        assert_eq!(assembly.base(), "GRCh38(chrX)");
    }

    #[test]
    fn test_accession_full() {
        let acc = Accession::new("NM", "000088", Some(3));
        assert_eq!(acc.full(), "NM_000088.3");

        let no_version = Accession::new("NM", "000088", None);
        assert_eq!(no_version.full(), "NM_000088");

        let ensembl = Accession::with_style("ENST", "00000012345", Some(1), true);
        assert_eq!(ensembl.full(), "ENST00000012345.1");
    }

    // ============== LocEdit Tests ==============

    #[test]
    fn test_loc_edit_new() {
        use crate::hgvs::location::GenomePos;

        let loc_edit: LocEdit<GenomeInterval, NaEdit> = LocEdit::new(
            GenomeInterval::point(GenomePos::new(100)),
            NaEdit::Deletion {
                sequence: None,
                length: None,
            },
        );
        assert!(matches!(loc_edit.edit, Mu::Certain(_)));
    }

    #[test]
    fn test_loc_edit_with_uncertainty() {
        use crate::hgvs::location::GenomePos;

        let loc_edit: LocEdit<GenomeInterval, NaEdit> = LocEdit::with_uncertainty(
            GenomeInterval::point(GenomePos::new(100)),
            Mu::Uncertain(NaEdit::Deletion {
                sequence: None,
                length: None,
            }),
        );
        assert!(matches!(loc_edit.edit, Mu::Uncertain(_)));
    }

    // ============== AllelePhase Tests ==============

    #[test]
    fn test_allele_phase_display() {
        assert_eq!(format!("{}", AllelePhase::Cis), "cis");
        assert_eq!(format!("{}", AllelePhase::Trans), "trans");
        assert_eq!(format!("{}", AllelePhase::Unknown), "unknown");
        assert_eq!(format!("{}", AllelePhase::Mosaic), "mosaic");
        assert_eq!(format!("{}", AllelePhase::Chimeric), "chimeric");
        assert_eq!(format!("{}", AllelePhase::AndOr), "and/or");
        assert_eq!(format!("{}", AllelePhase::Products), "products");
    }

    // ============== AlleleVariant Tests ==============

    #[test]
    fn test_allele_variant_unknown_phase() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        let var2 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(200)),
                NaEdit::Substitution {
                    reference: Base::C,
                    alternative: Base::T,
                },
            ),
        });

        let allele = AlleleVariant::unknown_phase(vec![var1, var2]);
        assert_eq!(allele.phase, AllelePhase::Unknown);
    }

    // ============== HgvsVariant Helper Tests ==============

    #[test]
    fn test_hgvs_variant_accession() {
        let variant = HgvsVariant::Genome(GenomeVariant {
            accession: Accession::new("NC", "000001", Some(11)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                GenomeInterval::point(GenomePos::new(12345)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });

        let acc = variant.accession().expect("Expected accession");
        assert_eq!(&*acc.prefix, "NC");
        assert_eq!(&*acc.number, "000001");
    }

    #[test]
    fn test_hgvs_variant_is_allele() {
        use crate::hgvs::location::CdsPos;

        let var1 = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        assert!(!var1.is_allele());

        let allele = AlleleVariant::cis(vec![var1.clone()]);
        let allele_variant = HgvsVariant::Allele(allele);
        assert!(allele_variant.is_allele());
    }

    #[test]
    fn test_hgvs_variant_protein_type() {
        use crate::hgvs::location::{AminoAcid, ProtPos};

        let protein = HgvsVariant::Protein(ProteinVariant {
            accession: Accession::new("NP", "000079", Some(2)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                ProtInterval::point(ProtPos::new(AminoAcid::Val, 600)),
                ProteinEdit::Substitution {
                    reference: AminoAcid::Val,
                    alternative: AminoAcid::Glu,
                },
            ),
        });
        assert_eq!(protein.variant_type(), "p");
        assert!(matches!(protein, HgvsVariant::Protein(_)));

        let genomic = HgvsVariant::Genome(GenomeVariant {
            accession: Accession::new("NC", "000001", Some(11)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                GenomeInterval::point(GenomePos::new(12345)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        assert_eq!(genomic.variant_type(), "g");
        assert!(!matches!(genomic, HgvsVariant::Protein(_)));
    }

    #[test]
    fn test_hgvs_variant_variant_type() {
        let genomic = HgvsVariant::Genome(GenomeVariant {
            accession: Accession::new("NC", "000001", Some(11)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                GenomeInterval::point(GenomePos::new(12345)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        assert_eq!(genomic.variant_type(), "g");

        use crate::hgvs::location::CdsPos;
        let cds = HgvsVariant::Cds(CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: None,
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        });
        assert_eq!(cds.variant_type(), "c");
    }

    #[test]
    fn test_cds_variant_with_gene_symbol() {
        use crate::hgvs::location::CdsPos;

        let variant = CdsVariant {
            accession: Accession::new("NM", "000088", Some(3)),
            gene_symbol: Some("COL1A1".to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(100)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        };

        // Per #1051: on a transcript reference (`NM_`) the gene-symbol selector
        // is disallowed by refseq.md, so Display emits the canonical bare form.
        // The value stays on the struct for programmatic access.
        assert_eq!(variant.gene_symbol, Some("COL1A1".to_string()));
        let display = format!("{}", variant);
        assert_eq!(display, "NM_000088.3:c.100A>G");
    }

    /// Build the `c.<position>A>G` substitution carrying `accession` and
    /// `gene_symbol`, for the selector-visibility tests below.
    fn cds_sub_with_gene(accession: Accession, gene_symbol: &str, position: i64) -> CdsVariant {
        use crate::hgvs::location::CdsPos;

        CdsVariant {
            accession,
            gene_symbol: Some(gene_symbol.to_string()),
            loc_edit: LocEdit::new(
                CdsInterval::point(CdsPos::new(position)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        }
    }

    #[test]
    fn test_gene_selector_suppressed_on_compound_reference_with_custom_transcript() {
        // #1139: a compound `genomic(transcript)` accession already carries the
        // single specification `refseq.md:40-41` permits. Appending the gene
        // symbol would stack a second group — non-conformant, and rejected by
        // ferro's own parser. The custom inner accession (`Template-gene.1`) is
        // the case the `is_transcript_reference` prefix whitelist misses.
        let accession = Accession::with_style("Template-gene", "", Some(1), true)
            .with_genomic_context(Accession::with_style("Template", "", None, true));
        let variant = cds_sub_with_gene(accession, "GENE1", 5);

        assert_eq!(variant.gene_symbol, Some("GENE1".to_string()));
        assert_eq!(format!("{}", variant), "Template(Template-gene.1):c.5A>G");
    }

    #[test]
    fn test_gene_selector_suppressed_on_compound_reference_with_nontranscript_inner() {
        // The suppression is a property of the *spent specification slot*, not
        // of the inner accession's type: `NG_` is not a transcript reference, so
        // the `is_transcript_reference` gate alone would emit `(GENE)` and stack
        // a second group.
        let accession = Accession::new("NG", "012232", Some(1))
            .with_genomic_context(Accession::new("NC", "000013", Some(11)));
        let variant = cds_sub_with_gene(accession, "BRCA1", 100);
        assert_eq!(format!("{}", variant), "NC_000013.11(NG_012232.1):c.100A>G");
    }

    #[test]
    fn test_protein_allele_with_gene_mismatch_compacts() {
        // #1142 made the `p.` selector invisible in `write_compact_prefix` but
        // left the compaction gates keyed on the accession alone, so a protein
        // allele whose members disagree on an *invisible* selector rendered
        // expanded — and its reparse (all-`None` genes) then compacted, making
        // Display non-idempotent (#1058). `gene_selector_visible` carries the
        // `p.` rule into the gates, so the mismatch no longer blocks compaction.
        use crate::hgvs::edit::ProteinEdit;
        use crate::hgvs::interval::ProtInterval;
        use crate::hgvs::location::{AminoAcid, ProtPos};

        let member = |gene: &str, pos: u64| {
            HgvsVariant::Protein(ProteinVariant {
                accession: Accession::new("NP", "003997", Some(2)),
                gene_symbol: Some(gene.to_string()),
                loc_edit: LocEdit::new_predicted(
                    ProtInterval::point(ProtPos::new(AminoAcid::Phe, pos)),
                    ProteinEdit::Identity {
                        predicted: true,
                        whole_protein: false,
                    },
                ),
            })
        };
        let allele = HgvsVariant::Allele(AlleleVariant::cis(vec![
            member("GENE1", 41),
            member("GENE2", 47),
        ]));
        assert_eq!(
            allele.to_string(),
            "NP_003997.2:p.[(Phe41(=));(Phe47(=))]",
            "an invisible selector mismatch must not block compaction",
        );
    }

    #[test]
    fn test_gene_selector_preserved_on_bare_genomic_reference() {
        // The spec-sanctioned form where the gene stands in for a transcript on
        // a genomic reference is untouched: no genomic context is present, so
        // the selector is the accession's only specification.
        let variant = cds_sub_with_gene(Accession::new("NC", "000023", Some(10)), "DMD", 5);
        assert_eq!(format!("{}", variant), "NC_000023.10(DMD):c.5A>G");
    }

    #[test]
    fn test_allele_compact_form_compound_custom_ref_compacts_despite_gene_mismatch() {
        // Display idempotency (#1058) for the #1139 case: the selector is
        // invisible on a compound reference, so a differing selector must not
        // block compaction — otherwise the expanded form reparses to all-`None`
        // genes and then compacts, making Display non-idempotent.
        let accession = Accession::with_style("Template-gene", "", Some(1), true)
            .with_genomic_context(Accession::with_style("Template", "", None, true));
        let cis = AlleleVariant::cis(vec![
            HgvsVariant::Cds(cds_sub_with_gene(accession.clone(), "GENE1", 100)),
            HgvsVariant::Cds(cds_sub_with_gene(accession, "GENE2", 200)),
        ]);
        assert_eq!(
            format!("{}", HgvsVariant::Allele(cis)),
            "Template(Template-gene.1):c.[100A>G;200A>G]"
        );
    }

    #[test]
    fn test_genome_variant_with_gene_symbol() {
        let variant = GenomeVariant {
            accession: Accession::new("NC", "000001", Some(11)),
            gene_symbol: Some("BRCA1".to_string()),
            loc_edit: LocEdit::new(
                GenomeInterval::point(GenomePos::new(12345)),
                NaEdit::Substitution {
                    reference: Base::A,
                    alternative: Base::G,
                },
            ),
        };

        // Per #121: Display preserves the gene-symbol selector when set.
        assert_eq!(variant.gene_symbol, Some("BRCA1".to_string()));
        let display = format!("{}", variant);
        assert_eq!(display, "NC_000001.11(BRCA1):g.12345A>G");
    }

    #[test]
    fn test_transcript_accession_bare() {
        let acc = Accession::new("NM", "004119", Some(3));
        assert_eq!(acc.transcript_accession(), "NM_004119.3");
        assert_eq!(acc.full(), "NM_004119.3");
    }

    #[test]
    fn test_transcript_accession_with_genomic_context() {
        let inner = Accession::new("NM", "004119", Some(3));
        let outer = Accession::new("NC", "000013", Some(11));
        let compound = inner.with_genomic_context(outer);

        // full() includes the compound wrapper
        assert_eq!(compound.full(), "NC_000013.11(NM_004119.3)");
        // transcript_accession() returns just the bare inner accession
        assert_eq!(compound.transcript_accession(), "NM_004119.3");
    }

    #[test]
    fn test_transcript_accession_assembly_ref() {
        let acc = Accession::from_assembly("GRCh38", "chr1");
        assert_eq!(acc.transcript_accession(), "GRCh38(chr1)");
    }

    #[test]
    fn test_transcript_accession_ensembl_with_context() {
        let inner = Accession::with_style("ENST", "00000241453", Some(7), true);
        let outer = Accession::new("NC", "000013", Some(11));
        let compound = inner.with_genomic_context(outer);

        assert_eq!(compound.full(), "NC_000013.11(ENST00000241453.7)");
        assert_eq!(compound.transcript_accession(), "ENST00000241453.7");
    }

    // ----- Issue #1059: coordinate-axis resolution -----

    use crate::hgvs::parser::variant::parse_variant;

    #[test]
    fn test_coordinate_axis_leaf_kinds() {
        let cases = [
            ("NM_000088.3:c.459A>G", CoordinateAxis::Coding),
            ("NC_000001.11:g.12345A>G", CoordinateAxis::Genomic),
            ("NR_003286.2:n.100A>G", CoordinateAxis::NonCoding),
            ("NM_000088.3:r.100a>g", CoordinateAxis::Rna),
            ("NP_000079.2:p.Arg8Gln", CoordinateAxis::Protein),
            ("NC_012920.1:m.100A>G", CoordinateAxis::Mitochondrial),
        ];
        for (input, expected) in cases {
            let v = parse_variant(input).unwrap();
            assert_eq!(
                v.coordinate_axis(),
                Some(expected),
                "{input} should resolve to axis {expected:?}"
            );
        }
    }

    #[test]
    fn test_coordinate_axis_allele_shares_member_axis() {
        // The reported case: an allele's parent must report its members' shared axis.
        let coding = parse_variant("NM_000000.1:c.[6G>C;16_18del]").unwrap();
        assert_eq!(coding.coordinate_axis(), Some(CoordinateAxis::Coding));

        let genomic = parse_variant("NC_000000.1:g.[6G>C;16_18del]").unwrap();
        assert_eq!(genomic.coordinate_axis(), Some(CoordinateAxis::Genomic));

        let protein = parse_variant("NP_000000.1:p.[(Arg8Gln);(Ser10Gly)]").unwrap();
        assert_eq!(protein.coordinate_axis(), Some(CoordinateAxis::Protein));
    }

    #[test]
    fn test_coordinate_axis_mixed_allele_is_none() {
        // A synthesized allele whose members disagree on axis has no single axis.
        let cds = parse_variant("NM_004006.2:c.100_150del").unwrap();
        let tx = parse_variant("NM_004006.2:n.100_150dup").unwrap();
        let mixed = HgvsVariant::Allele(AlleleVariant::new(vec![cds, tx], AllelePhase::Cis));
        assert_eq!(mixed.coordinate_axis(), None);
    }

    #[test]
    fn test_coordinate_axis_markers_contribute_no_axis() {
        // Bare [0] / [?] markers have no axis at all.
        assert_eq!(HgvsVariant::NullAllele.coordinate_axis(), None);
        assert_eq!(HgvsVariant::UnknownAllele.coordinate_axis(), None);

        // A trans allele mixing a concrete coding member with a [?] marker still
        // resolves to the concrete member's axis (the marker is skipped).
        let concrete = parse_variant("NM_000088.3:c.459A>G").unwrap();
        let with_marker = HgvsVariant::Allele(AlleleVariant::new(
            vec![concrete, HgvsVariant::UnknownAllele],
            AllelePhase::Trans,
        ));
        assert_eq!(with_marker.coordinate_axis(), Some(CoordinateAxis::Coding));
    }

    #[test]
    fn test_coordinate_axis_nested_allele() {
        // and/or alleles nest one level: the parent must recurse into sub-alleles.
        let a = parse_variant("NM_000088.3:c.459A>G").unwrap();
        let b = parse_variant("NM_000088.3:c.500A>G").unwrap();
        let inner = HgvsVariant::Allele(AlleleVariant::new(vec![a, b], AllelePhase::Cis));
        let outer = HgvsVariant::Allele(AlleleVariant::new(vec![inner], AllelePhase::Cis));
        assert_eq!(outer.coordinate_axis(), Some(CoordinateAxis::Coding));
    }

    #[test]
    fn test_coordinate_axis_genome_ring_is_genomic() {
        // A genome ring (`ACC:g.[seg1::seg2]`) is a single genomic accession
        // whose `::` are intra-molecule ISCN2020 break junctions — not a fusion
        // of two frames — so it resolves to Genomic, unlike an RNA fusion.
        let ring = parse_variant("NC_000022.11:g.pter_1000del::2000_qterdel").unwrap();
        assert!(
            matches!(ring, HgvsVariant::GenomeRing(_)),
            "expected a GenomeRing, got {ring:?}"
        );
        assert_eq!(ring.coordinate_axis(), Some(CoordinateAxis::Genomic));
    }

    #[test]
    fn test_coordinate_axis_enum_groupings() {
        assert_eq!(CoordinateAxis::Coding.code(), "c");
        assert_eq!(CoordinateAxis::Genomic.code(), "g");
        assert_eq!(CoordinateAxis::NonCoding.code(), "n");
        assert_eq!(CoordinateAxis::Rna.code(), "r");
        assert_eq!(CoordinateAxis::Protein.code(), "p");
        assert_eq!(CoordinateAxis::Mitochondrial.code(), "m");
        assert_eq!(CoordinateAxis::Circular.code(), "o");

        // DNA axes: g / c / n / m / o. RNA: r. Protein: p.
        for dna in [
            CoordinateAxis::Genomic,
            CoordinateAxis::Coding,
            CoordinateAxis::NonCoding,
            CoordinateAxis::Mitochondrial,
            CoordinateAxis::Circular,
        ] {
            assert!(dna.is_dna(), "{dna:?} should be DNA");
            assert!(!dna.is_rna());
            assert!(!dna.is_protein());
        }
        assert!(CoordinateAxis::Rna.is_rna());
        assert!(!CoordinateAxis::Rna.is_dna());
        assert!(CoordinateAxis::Protein.is_protein());
        assert!(!CoordinateAxis::Protein.is_dna());
    }

    // ----- Issue #115: self-cancelling allele detection (E3006) -----

    #[test]
    fn test_self_cancelling_detect_spec_example() {
        // Spec example: c.[762_768del;767_774dup]
        let del = parse_variant("NM_004006.2:c.762_768del").unwrap();
        let dup = parse_variant("NM_004006.2:c.767_774dup").unwrap();
        let pair = AlleleVariant::detect_self_cancelling_pair(&[del, dup]);
        assert!(
            pair.is_some(),
            "spec-example overlapping del+dup must be detected"
        );
        let (dl, du) = pair.unwrap();
        assert_eq!(dl, 0, "first index is the del");
        assert_eq!(du, 1, "second index is the dup");
    }

    #[test]
    fn test_self_cancelling_no_overlap() {
        let del = parse_variant("NM_004006.2:c.100_110del").unwrap();
        let dup = parse_variant("NM_004006.2:c.500_510dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none());
    }

    #[test]
    fn test_self_cancelling_two_dels() {
        let a = parse_variant("NM_004006.2:c.100_110del").unwrap();
        let b = parse_variant("NM_004006.2:c.105_115del").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[a, b]).is_none());
    }

    #[test]
    fn test_self_cancelling_different_accessions() {
        let del = parse_variant("NM_004006.2:c.100_110del").unwrap();
        let dup = parse_variant("NM_000088.3:c.105_115dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none());
    }

    #[test]
    fn test_self_cancelling_dup_first_then_del() {
        // Order in the allele shouldn't matter; the dup-first variant is
        // still a self-cancelling pair.
        let dup = parse_variant("NM_004006.2:c.767_774dup").unwrap();
        let del = parse_variant("NM_004006.2:c.762_768del").unwrap();
        let pair = AlleleVariant::detect_self_cancelling_pair(&[dup, del]);
        assert!(pair.is_some());
        let (dl, du) = pair.unwrap();
        assert_eq!(dl, 1, "del is at index 1");
        assert_eq!(du, 0, "dup is at index 0");
    }

    #[test]
    fn test_self_cancelling_genomic_overlap() {
        let del = parse_variant("NC_000017.11:g.43044295_43044300del").unwrap();
        let dup = parse_variant("NC_000017.11:g.43044298_43044305dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some());
    }

    // ----- Issue #172: extend E3006 to *-region and intronic ranges -----

    #[test]
    fn test_self_cancelling_cds_3utr_star_overlap() {
        // 3'UTR (`c.*N`) range; HGVS general.md line 58 forbids overlapping
        // del+dup just as much in *-region as in the CDS proper.
        let del = parse_variant("NM_004006.2:c.*100_*150del").unwrap();
        let dup = parse_variant("NM_004006.2:c.*145_*160dup").unwrap();
        let pair = AlleleVariant::detect_self_cancelling_pair(&[del, dup]);
        assert!(
            pair.is_some(),
            "overlapping 3'UTR del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_cds_3utr_star_no_overlap() {
        // Non-overlapping 3'UTR pair: spec-permitted.
        let del = parse_variant("NM_004006.2:c.*100_*110del").unwrap();
        let dup = parse_variant("NM_004006.2:c.*200_*210dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none());
    }

    #[test]
    fn test_self_cancelling_cds_intronic_offset_overlap() {
        // Intronic offsets on a CDS-relative axis (`c.100+5`).
        let del = parse_variant("NM_004006.2:c.100+5_100+15del").unwrap();
        let dup = parse_variant("NM_004006.2:c.100+12_100+20dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping intronic del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_cds_intronic_offset_no_overlap() {
        // Same anchor, non-overlapping intronic offsets.
        let del = parse_variant("NM_004006.2:c.100+5_100+10del").unwrap();
        let dup = parse_variant("NM_004006.2:c.100+15_100+20dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none());
    }

    #[test]
    fn test_self_cancelling_tx_intronic_overlap() {
        // Tx axis (`n.`) intronic case.
        let del = parse_variant("NR_001234.1:n.100+5_100+15del").unwrap();
        let dup = parse_variant("NR_001234.1:n.100+12_100+20dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping tx intronic del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_cds_cross_region_no_overlap() {
        // 5'UTR del (negative base) and 3'UTR dup (`*` region) are on
        // disjoint regions even if their numeric bases coincide; must
        // NOT be reported as overlapping.
        let del = parse_variant("NM_004006.2:c.-50_-40del").unwrap();
        let dup = parse_variant("NM_004006.2:c.*40_*50dup").unwrap();
        assert!(AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none());
    }

    #[test]
    fn test_parse_self_cancelling_cds_3utr_rejected_via_parser() {
        // End-to-end: the parser-level validator must reject the same
        // overlapping 3'UTR pair with E3006.
        let result = parse_variant("NM_004006.2:c.[*100_*150del;*145_*160dup]");
        let err = result.expect_err("3'UTR overlapping del+dup must reject");
        assert_eq!(
            err.code(),
            Some(crate::error::ErrorCode::SelfCancellingAllele)
        );
    }

    #[test]
    fn test_parse_self_cancelling_cds_intronic_rejected_via_parser() {
        let result = parse_variant("NM_004006.2:c.[100+5_100+15del;100+12_100+20dup]");
        let err = result.expect_err("intronic overlapping del+dup must reject");
        assert_eq!(
            err.code(),
            Some(crate::error::ErrorCode::SelfCancellingAllele)
        );
    }

    #[test]
    fn test_self_cancelling_cds_5utr_overlap() {
        // 5'UTR positions (negative `base`) overlap by lex order on
        // `(false, base, 0)`; positive-result coverage for the cross-region
        // negative test above.
        let del = parse_variant("NM_004006.2:c.-50_-30del").unwrap();
        let dup = parse_variant("NM_004006.2:c.-35_-20dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping 5'UTR del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_cds_negative_intronic_offset_overlap() {
        // `c.X-N` offsets are on the same intron as `c.(X-1)+M`, and
        // lex-order on `(false, X, -N)` correctly places them.
        let del = parse_variant("NM_004006.2:c.100-15_100-5del").unwrap();
        let dup = parse_variant("NM_004006.2:c.100-10_100-2dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping negative-intronic-offset del+dup must be detected"
        );
    }

    #[test]
    fn test_self_cancelling_cds_cross_exon_intronic_range_ok() {
        // Two non-overlapping ranges on opposite sides of the intron
        // midpoint do NOT collide.
        let del = parse_variant("NM_004006.2:c.99+1_99+10del").unwrap();
        let dup = parse_variant("NM_004006.2:c.100-10_100-1dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none(),
            "non-overlapping cross-exon intronic ranges must NOT collide"
        );
    }

    #[test]
    fn test_self_cancelling_rna_intronic_overlap() {
        // r. axis intronic overlap — same shape as c.X+N but with the RNA
        // coordinate system. RNA descriptions are canonically lowercase.
        let del = parse_variant("NM_004006.2:r.100+5_100+15del").unwrap();
        let dup = parse_variant("NM_004006.2:r.100+12_100+20dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping r. intronic del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_tx_downstream_star_overlap() {
        // `n.*N` downstream positions are the tx-axis analogue of c.*N.
        //
        // #1748 refuses that spelling at parse in every mode, so both members
        // are constructed. The detector still has to handle them —
        // `TxPos::downstream` is public API — and an overlap that arrives by
        // construction rather than by parse is exactly the case a
        // parse-stage refusal cannot cover.
        let del = tx_downstream_range("NR_001234.1", 100, 150, "del");
        let dup = tx_downstream_range("NR_001234.1", 145, 160, "dup");
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_some(),
            "overlapping n. downstream del+dup must be detected (#172)"
        );
    }

    #[test]
    fn test_self_cancelling_unknown_base_skipped() {
        // `c.?` (unknown base) makes overlap undecidable; the detector
        // must skip the variant rather than emit a false positive.
        let del = parse_variant("NM_004006.2:c.?_200del").unwrap();
        let dup = parse_variant("NM_004006.2:c.150_160dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none(),
            "pair containing c.? must be skipped (undecidable)"
        );
    }

    #[test]
    fn test_self_cancelling_unknown_offset_sentinel_skipped() {
        // `c.X+?` parses to an offset sentinel (`i64::MAX`); treat it as
        // undecidable rather than letting the sentinel poison the lex
        // order.
        let del = parse_variant("NM_004006.2:c.100+?_300del").unwrap();
        let dup = parse_variant("NM_004006.2:c.150_160dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none(),
            "pair containing `+?` offset sentinel must be skipped"
        );
    }

    #[test]
    fn test_self_cancelling_mixed_axis_same_accession_no_false_positive() {
        // CodeRabbit #371: an accession (NM_*) carries both `c.` (CDS) and
        // `n.` / `r.` (tx / RNA) coordinate systems. A `c.` del and an
        // `n.` dup with the same numeric range live in disjoint coordinate
        // continua and MUST NOT be reported as self-cancelling, even
        // though they share `acc.full()`. The detector must gate on axis
        // identity before comparing canonical ranges.
        let del_cds = parse_variant("NM_004006.2:c.100_150del").unwrap();
        let dup_tx = parse_variant("NM_004006.2:n.100_150dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del_cds, dup_tx]).is_none(),
            "c. del and n. dup with matching numeric ranges must NOT collide \
             (different coordinate axes)"
        );

        // Cover the c./r. pairing too — same accession, different axis.
        let del_cds2 = parse_variant("NM_004006.2:c.100_150del").unwrap();
        let dup_rna = parse_variant("NM_004006.2:r.100_150dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del_cds2, dup_rna]).is_none(),
            "c. del and r. dup with matching numeric ranges must NOT collide \
             (different coordinate axes)"
        );

        // Cover the n./r. pairing — both `region`-bearing axes but
        // numerically different coordinate systems.
        let del_tx = parse_variant("NM_004006.2:n.100_150del").unwrap();
        let dup_rna2 = parse_variant("NM_004006.2:r.100_150dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del_tx, dup_rna2]).is_none(),
            "n. del and r. dup with matching numeric ranges must NOT collide \
             (different coordinate axes)"
        );
    }

    #[test]
    fn test_self_cancelling_genomic_vs_mito_no_false_positive() {
        // Genome and mito axes are both `region=false` in the canonical
        // representation; without an axis gate they would collide on
        // identical numeric ranges. Practical exposure is low (the same
        // accession won't appear as both g. and m. in real data), but
        // `detect_self_cancelling_pair` is a public API that operates on
        // a raw slice — synthesize the mismatch directly.
        let del = parse_variant("NC_000017.11:g.43044295_43044300del").unwrap();
        let dup = parse_variant("NC_000017.11:m.43044295_43044300dup").unwrap();
        assert!(
            AlleleVariant::detect_self_cancelling_pair(&[del, dup]).is_none(),
            "g. and m. variants with matching numeric ranges must NOT collide"
        );
    }

    #[test]
    fn test_protein_variant_to_styled_string() {
        use crate::hgvs::location::{AaCode, ProteinRenderStyle, TerStyle};
        use crate::parse_hgvs;

        let three_star = ProteinRenderStyle {
            stop: TerStyle::Star,
            aa_code: AaCode::Three,
        };
        let one = ProteinRenderStyle {
            stop: TerStyle::Ter,
            aa_code: AaCode::One,
        };

        let cases = [
            // (input, three_star expected, one expected)
            (
                "NP_000079.2:p.(Ser4Thr)",
                "NP_000079.2:p.(Ser4Thr)",
                "NP_000079.2:p.(S4T)",
            ),
            (
                "NP_000079.2:p.(Ile50Ter)",
                "NP_000079.2:p.(Ile50*)",
                "NP_000079.2:p.(I50*)",
            ),
            (
                "NP_000079.2:p.(Ser4LeufsTer76)",
                "NP_000079.2:p.(Ser4Leufs*76)",
                "NP_000079.2:p.(S4Lfs*76)",
            ),
            (
                "NP_000079.2:p.Met1ext-5",
                "NP_000079.2:p.Met1ext-5",
                "NP_000079.2:p.M1ext-5",
            ),
        ];
        for (input, want_star, want_one) in cases {
            let v = parse_hgvs(input).expect("parse");
            assert_eq!(v.to_styled_string(three_star), want_star, "star: {input}");
            assert_eq!(v.to_styled_string(one), want_one, "one: {input}");
            // default equals Display
            assert_eq!(
                v.to_styled_string(ProteinRenderStyle::default()),
                v.to_string(),
                "default: {input}"
            );
        }
    }

    #[test]
    fn test_hgvs_variant_to_styled_string_non_protein_passthrough() {
        use crate::hgvs::location::{AaCode, ProteinRenderStyle, TerStyle};
        use crate::parse_hgvs;
        // Non-protein variants ignore the style and equal Display.
        let one = ProteinRenderStyle {
            stop: TerStyle::Star,
            aa_code: AaCode::One,
        };
        let v = parse_hgvs("NM_000088.3:c.459A>G").expect("parse");
        assert_eq!(v.to_styled_string(one), v.to_string());
    }

    /// `spec_equivalent_renderings` offers the `*` spelling for exactly those
    /// descriptions whose rendering contains a stop token, and nothing else.
    #[test]
    fn spec_equivalent_renderings_offers_the_star_stop_spelling() {
        use crate::parse_hgvs;
        for (input, want) in [
            // A stop token anywhere in the rendering — plain, frameshift and
            // extension shapes, plus a stop inside a cis allele.
            ("NP_000079.2:p.Trp24Ter", Some("NP_000079.2:p.Trp24*")),
            (
                "NP_000079.2:p.Gln151ThrfsTer9",
                Some("NP_000079.2:p.Gln151Thrfs*9"),
            ),
            (
                "NP_000079.2:p.Ter110GlnextTer17",
                Some("NP_000079.2:p.*110Glnext*17"),
            ),
            (
                "NP_000079.2:p.[Lys79Ter;Lys79Asn]",
                Some("NP_000079.2:p.[Lys79*;Lys79Asn]"),
            ),
            // Protein, but no stop token: nothing to respell.
            ("NP_000079.2:p.(Ser4Thr)", None),
            // Off the protein axis the stop style has no meaning at all.
            ("NM_000088.3:c.459A>G", None),
            ("NC_000023.11:g.32867861_32867862del", None),
        ] {
            let v = parse_hgvs(input).expect("parse");
            let got = v.spec_equivalent_renderings();
            match want {
                Some(starred) => assert_eq!(got, vec![starred.to_string()], "for {input}"),
                None => assert!(
                    got.is_empty(),
                    "expected no alternate rendering for {input}, got {got:?}"
                ),
            }
        }
    }

    /// The alternates are *additional* spellings, never a replacement: the
    /// canonical `Display` form must not appear among them, or a caller checking
    /// "does this name my variant?" would count the same spelling twice.
    #[test]
    fn spec_equivalent_renderings_excludes_the_canonical_form() {
        use crate::parse_hgvs;
        for input in [
            "NP_000079.2:p.Trp24Ter",
            "NP_000079.2:p.(Ser4Thr)",
            "NM_000088.3:c.459A>G",
        ] {
            let v = parse_hgvs(input).expect("parse");
            let canonical = v.to_string();
            assert!(
                !v.spec_equivalent_renderings().contains(&canonical),
                "{input}: alternates must exclude the canonical rendering"
            );
        }
    }

    #[test]
    fn test_styled_default_equals_display_corpus() {
        use crate::hgvs::location::ProteinRenderStyle;
        use crate::parse_hgvs;
        let corpus = [
            "NP_000079.2:p.(Ser4Thr)",
            "NP_000079.2:p.Ile50Ter",
            "NP_000079.2:p.Ser4LeufsTer76",
            "NP_000079.2:p.Gly719(Ala^Ser)fsTer23",
            "NP_000079.2:p.Ter110GlnextTer17",
            "NP_000079.2:p.Met1ext-5",
            "NP_000079.2:p.Lys23_Leu24insTer12",
            // Same interval-deletion shape as the spec's delQRGEPG example, but
            // parser-accepted (the explicit deleted-sequence form is rejected).
            "NP_000079.2:p.Gln367_Gly372del",
            "NP_000079.2:p.=",
            "NP_000079.2:p.0",
            "NP_000079.2:p.(=)",
            "NP_000079.2:p.?",
        ];
        for input in corpus {
            let v = parse_hgvs(input).expect("parse");
            assert_eq!(
                v.to_styled_string(ProteinRenderStyle::default()),
                v.to_string(),
                "default style must equal Display for {input}"
            );
        }
    }

    /// `non_flanking_genomic_insertion_anchor` must classify every representable
    /// position pair, including one anchored at `u64::MAX`.
    ///
    /// The parser accepts any `u64` position, so `g.<u64::MAX>_<u64::MAX-1>insA`
    /// is reachable from public input. Asking "is `end` one past `start`?" as
    /// `end.base != start.base + 1` overflows on that pair — a panic in
    /// overflow-checked builds, a wrap in release ones, where the answer is
    /// plainly "no, it is not flanking".
    #[test]
    fn the_insertion_anchor_check_survives_a_position_at_the_top_of_the_range() {
        use crate::hgvs::parser::parse_hgvs;

        let v =
            parse_hgvs("NC_TEST.1:g.18446744073709551615_18446744073709551614insA").expect("parse");
        assert_eq!(
            non_flanking_genomic_insertion_anchor(&v),
            Some((u64::MAX, u64::MAX - 1)),
        );
    }
}