ferro-hgvs 0.6.0

HGVS variant normalizer - part of the ferro bioinformatics toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
//! Full variant parsing
//!
//! Parses complete HGVS variant strings into the HgvsVariant type.

use crate::error::FerroError;
use crate::hgvs::edit::ProteinEdit;
use crate::hgvs::interval::{
    CdsInterval, GenomeInterval, Interval, ProtInterval, RnaInterval, TxInterval, UncertainBoundary,
};
use crate::hgvs::location::{AminoAcid, CdsPos, ProtPos};
use crate::hgvs::parser::accession::{parse_accession, parse_gene_symbol};
use crate::hgvs::parser::edit::{parse_na_edit, parse_protein_edit};
use crate::hgvs::parser::position::{
    parse_amino_acid, parse_cds_pos, parse_genome_pos, parse_prot_pos, parse_rna_pos, parse_tx_pos,
};
use crate::hgvs::uncertainty::Mu;
use crate::hgvs::variant::{
    Accession, AllelePhase, AlleleVariant, CdsVariant, CircularVariant, GenomeVariant, HgvsVariant,
    LocEdit, MtVariant, ProteinVariant, RnaFusionBreakpoint, RnaFusionVariant, RnaVariant,
    TxVariant,
};
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{char, digit1},
    combinator::map,
    sequence::{delimited, preceded},
    IResult, Parser,
};

fn parse_uncertain_tx_pos(input: &str) -> IResult<&str, Mu<crate::hgvs::location::TxPos>> {
    alt((
        // Unknown: ?
        map(tag("?"), |_| Mu::Unknown),
        map(delimited(char('('), parse_tx_pos, char(')')), Mu::uncertain),
        map(parse_tx_pos, Mu::certain),
    ))
    .parse(input)
}

fn parse_uncertain_rna_pos(input: &str) -> IResult<&str, Mu<crate::hgvs::location::RnaPos>> {
    alt((
        // Unknown: ?
        map(tag("?"), |_| Mu::Unknown),
        map(
            delimited(char('('), parse_rna_pos, char(')')),
            Mu::uncertain,
        ),
        map(parse_rna_pos, Mu::certain),
    ))
    .parse(input)
}

/// Parse (pos_pos) with intronic offsets as a range boundary inner
fn parse_cds_intronic_range_inner(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::CdsPos>> {
    let (remaining, (start, _, end)) = (parse_cds_pos, tag("_"), parse_cds_pos).parse(input)?;
    // Only treat as range boundary if at least one has intronic offset
    if start.offset.is_some() || end.offset.is_some() {
        Ok((
            remaining,
            UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
        ))
    } else {
        Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )))
    }
}

/// Parse unparenthesized ?_pos pattern (e.g., ?_-540 in c.?_-540_3117+?del)
/// Only succeeds if the pattern is followed by another _ (indicating a range continuation)
fn parse_cds_unparenthesized_range_start(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::CdsPos>> {
    let (after_question, _) = tag::<_, _, nom::error::Error<&str>>("?_").parse(input)?;
    let (remaining, pos) = parse_cds_pos(after_question)?;
    // Only use this parser if followed by _ (indicating another position follows)
    if !remaining.starts_with('_') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }
    Ok((
        remaining,
        UncertainBoundary::range(Mu::Unknown, Mu::certain(pos)),
    ))
}

/// Parse a CDS range boundary: (?_pos), (pos_?), (pos_pos), or (pos+off_pos-off)
fn parse_cds_range_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::CdsPos>> {
    delimited(
        char('('),
        alt((
            // (?_pos)
            map((tag("?"), tag("_"), parse_cds_pos), |(_, _, end)| {
                UncertainBoundary::range(Mu::Unknown, Mu::certain(end))
            }),
            // (pos_?)
            map((parse_cds_pos, tag("_"), tag("?")), |(start, _, _)| {
                UncertainBoundary::range(Mu::certain(start), Mu::Unknown)
            }),
            // (pos_pos) with intronic offsets
            parse_cds_intronic_range_inner,
            // Simple range (pos_pos) without offsets - for uncertain boundaries like (4_6)
            map(
                (parse_cds_pos, tag("_"), parse_cds_pos),
                |(start, _, end)| UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
            ),
        )),
        char(')'),
    )
    .parse(input)
}

/// Parse a complex CDS boundary that can be a single position or a range
/// Handles: pos, (pos), ?, (?_pos), (pos_?), (pos+off_pos-off)
/// Note: (pos_pos) without offsets/unknowns is NOT parsed here - it's handled at the interval level.
/// Parse a CDS position boundary with optional uncertainty
/// Optimized: fast path for positions starting with digit, *, or -
#[inline]
fn parse_cds_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::CdsPos>> {
    let bytes = input.as_bytes();
    if bytes.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // Fast path: if starts with digit, *, or - it's likely a certain position
    if bytes[0].is_ascii_digit() || bytes[0] == b'*' || bytes[0] == b'-' {
        return map(parse_cds_pos, UncertainBoundary::certain).parse(input);
    }

    // Otherwise, try complex patterns
    alt((
        // Range boundary: (?_pos), (pos_?), or (pos+off_pos-off) with intronic offsets
        parse_cds_range_boundary,
        // Single uncertain position: (pos)
        map(
            delimited(char('('), parse_cds_pos, char(')')),
            UncertainBoundary::uncertain,
        ),
        // Unparenthesized ?_pos pattern (e.g., ?_-540 in ?_-540_3117+?del)
        // Only treat ?_pos as a range boundary if it's followed by another _
        // Otherwise ?_pos should be parsed as ? (start) and pos (end) of an interval
        parse_cds_unparenthesized_range_start,
        // Unknown: ?
        map(tag("?"), |_| UncertainBoundary::unknown()),
    ))
    .parse(input)
}

/// Parse a genome range boundary: (?_pos), (pos_?), or (pos_pos)
fn parse_genome_range_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::GenomePos>> {
    delimited(
        char('('),
        alt((
            // (?_pos)
            map((tag("?"), tag("_"), parse_genome_pos), |(_, _, end)| {
                UncertainBoundary::range(Mu::Unknown, Mu::certain(end))
            }),
            // (pos_?)
            map((parse_genome_pos, tag("_"), tag("?")), |(start, _, _)| {
                UncertainBoundary::range(Mu::certain(start), Mu::Unknown)
            }),
            // (pos_pos) - range with both positions known
            map(
                (parse_genome_pos, tag("_"), parse_genome_pos),
                |(start, _, end)| UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
            ),
        )),
        char(')'),
    )
    .parse(input)
}

/// Parse a complex genome boundary that can be a single position or a range
/// Only parses (?_pos) and (pos_?) as range boundaries - plain (pos_pos) is handled at interval level
/// Parse a genome position boundary with optional uncertainty
/// Optimized: fast path for simple digit positions (most common case)
#[inline]
fn parse_genome_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::GenomePos>> {
    let bytes = input.as_bytes();
    if bytes.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // Fast path: if starts with digit, it's a simple certain position
    if bytes[0].is_ascii_digit() {
        return map(parse_genome_pos, UncertainBoundary::certain).parse(input);
    }

    // Otherwise, try complex patterns
    alt((
        // Range boundary with unknown: (?_pos) or (pos_?)
        parse_genome_range_boundary,
        // Single uncertain position: (pos)
        map(
            delimited(char('('), parse_genome_pos, char(')')),
            UncertainBoundary::uncertain,
        ),
        // Unknown: ?
        map(tag("?"), |_| UncertainBoundary::unknown()),
    ))
    .parse(input)
}

/// Check if input starts with a special position marker (pter, qter, cen)
#[inline]
fn starts_with_special_pos(bytes: &[u8]) -> bool {
    (bytes.len() >= 4 && (bytes[0..4] == *b"pter" || bytes[0..4] == *b"qter"))
        || (bytes.len() >= 3 && bytes[0..3] == *b"cen")
}

/// Parse an interval (single position or range) with optional uncertainty
/// Supports complex boundaries like (pos_pos) ranges
/// Note: Inverted ranges (start > end) are rejected as invalid HGVS
/// Optimized: fast path for simple positions and ranges (starting with digit)
#[inline]
fn parse_genome_interval(input: &str) -> IResult<&str, GenomeInterval> {
    let bytes = input.as_bytes();
    if bytes.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // Fast path: if starts with digit or special position, it's a simple position or range
    if bytes[0].is_ascii_digit() || starts_with_special_pos(bytes) {
        let (remaining, start) = parse_genome_pos(input)?;
        // Check if this is a range (followed by _)
        if let Some(after_underscore) = remaining.strip_prefix('_') {
            // Use fast path if followed by another digit or special position
            let after_bytes = after_underscore.as_bytes();
            if !after_bytes.is_empty()
                && (after_bytes[0].is_ascii_digit() || starts_with_special_pos(after_bytes))
            {
                let (remaining, end) = parse_genome_pos(after_underscore)?;
                // Skip inverted range check if:
                // - either position is special (pter/qter have no comparable base values)
                // - the edit is a structural variant type that may use inverted coordinates
                //   (insertions, duplications, inversions, and complex delins)
                let allows_inverted = remaining.starts_with("dupins")
                    || remaining.starts_with("inv")
                    || remaining.starts_with("ins")
                    || remaining.starts_with("dup");
                if !start.is_special()
                    && !end.is_special()
                    && !allows_inverted
                    && start.base > end.base
                {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }
                return Ok((
                    remaining,
                    Interval::with_complex_boundaries(
                        UncertainBoundary::certain(start),
                        UncertainBoundary::certain(end),
                    ),
                ));
            }
            // Fall through to complex parser
        } else {
            // Single position (no underscore follows)
            return Ok((remaining, GenomeInterval::point(start)));
        }
    }

    // Complex cases: starts with ( or ?
    alt((
        // Simple uncertain interval: (pos_pos) NOT followed by _
        // This produces (pos)_(pos) in output
        |input| {
            let (remaining, (start, _, end)) = delimited(
                char('('),
                (parse_genome_pos, tag("_"), parse_genome_pos),
                char(')'),
            )
            .parse(input)?;
            // If followed by _, this is a complex boundary, not a simple uncertain interval
            if remaining.starts_with('_') {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            // Reject inverted ranges
            if start.base > end.base {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            Ok((
                remaining,
                Interval::with_uncertainty(Mu::uncertain(start), Mu::uncertain(end)),
            ))
        },
        // Complex interval with range boundaries: (start_boundary)_(end_boundary)
        // This handles patterns like: (?_100)_(200_?)del, (100_200)_(300_400)del
        |input| {
            let (remaining, (start, _, end)) =
                (parse_genome_boundary, tag("_"), parse_genome_boundary).parse(input)?;
            // For simple ranges with certain positions, reject inverted ranges
            if let (
                UncertainBoundary::Single(Mu::Certain(s)),
                UncertainBoundary::Single(Mu::Certain(e)),
            ) = (&start, &end)
            {
                if s.base > e.base {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }
            }
            Ok((remaining, Interval::with_complex_boundaries(start, end)))
        },
        // Single position (possibly uncertain, unknown, or a range boundary)
        map(parse_genome_boundary, |boundary| match boundary {
            UncertainBoundary::Single(Mu::Certain(inner)) => GenomeInterval::point(inner),
            UncertainBoundary::Single(Mu::Uncertain(inner)) => {
                Interval::with_uncertainty(Mu::uncertain(inner), Mu::uncertain(inner))
            }
            UncertainBoundary::Single(Mu::Unknown) => {
                Interval::with_uncertainty(Mu::Unknown, Mu::Unknown)
            }
            UncertainBoundary::Range { start, end } => {
                // A single range boundary used as a point - unusual but valid
                Interval::with_complex_boundaries(
                    UncertainBoundary::Range {
                        start: start.clone(),
                        end: end.clone(),
                    },
                    UncertainBoundary::Range { start, end },
                )
            }
        }),
    ))
    .parse(input)
}

/// Parse a simple uncertain CDS interval (pos_pos) NOT followed by _
/// This prevents eating the first boundary of a complex interval
fn parse_simple_uncertain_cds_interval(input: &str) -> IResult<&str, CdsInterval> {
    let (remaining, _) = char('(').parse(input)?;
    let (remaining, start) = parse_cds_pos(remaining)?;
    let (remaining, _) = tag("_").parse(remaining)?;
    let (remaining, end) = parse_cds_pos(remaining)?;
    let (remaining, _) = char(')').parse(remaining)?;

    // Check that this is NOT followed by _ (which would indicate a complex interval)
    if remaining.starts_with('_') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    // Only if NEITHER has an offset, treat as simple uncertain interval
    if start.offset.is_none() && end.offset.is_none() {
        Ok((
            remaining,
            Interval::with_uncertainty(Mu::uncertain(start), Mu::uncertain(end)),
        ))
    } else {
        // Check if followed by another parenthesized range without underscore
        // This handles patterns like (2727+1_2728-1)(2858+1_2859-1)
        if remaining.starts_with('(') {
            let (remaining2, _) = char('(').parse(remaining)?;
            let (remaining2, end_start) = parse_cds_pos(remaining2)?;
            let (remaining2, _) = tag("_").parse(remaining2)?;
            let (remaining2, end_end) = parse_cds_pos(remaining2)?;
            let (remaining2, _) = char(')').parse(remaining2)?;

            return Ok((
                remaining2,
                Interval::with_complex_boundaries(
                    UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
                    UncertainBoundary::range(Mu::certain(end_start), Mu::certain(end_end)),
                ),
            ));
        }

        // Has offsets - this is a single range boundary used as an interval
        // (unusual but valid - e.g., just "(100+1_101-1)del" as a point)
        Ok((
            remaining,
            Interval::with_complex_boundaries(
                UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
                UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
            ),
        ))
    }
}

/// Compare two CDS positions for ordering
/// Returns true if start > end (inverted range)
///
/// Note: When either position has an intronic offset, we cannot determine
/// the true genomic order without knowing intron lengths. In such cases,
/// we allow the range (return false) since patterns like c.85-47_84+48 are
/// valid intronic ranges that appear in databases like ExAC.
fn cds_pos_is_inverted(start: &CdsPos, end: &CdsPos) -> bool {
    // If either position is unknown (?), we can't determine order. Allow these ranges.
    if start.is_unknown() || end.is_unknown() {
        return false;
    }

    // If either position has an intronic offset, we can't reliably determine
    // the genomic order without knowing the intron length. Allow these ranges.
    if start.offset.is_some() || end.offset.is_some() {
        return false;
    }

    // UTR ordering: 5' UTR < CDS < 3' UTR
    // 5' UTR has utr3=false and negative base
    // CDS has utr3=false and positive base
    // 3' UTR has utr3=true

    // Different regions
    if start.utr3 != end.utr3 {
        // 3' UTR (utr3=true) is always after 5' UTR or CDS
        // So start=3'UTR, end=5'UTR/CDS is inverted
        return start.utr3;
    }

    // Same UTR region - compare bases
    if start.utr3 {
        // Both in 3' UTR: *1 < *100
        start.base > end.base
    } else {
        // 5' UTR or CDS: -100 < -1 < 1 < 100
        start.base > end.base
    }
}

/// Parse a CDS interval with support for complex boundaries
/// Note: Inverted ranges (start > end) are rejected as invalid HGVS
/// Parse a CDS interval
/// Optimized: fast path for simple positions (starting with digit, *, or -)
#[inline]
fn parse_cds_interval(input: &str) -> IResult<&str, CdsInterval> {
    let bytes = input.as_bytes();
    if bytes.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // Fast path: if starts with digit, *, or - it's a simple position or range
    // Also handle ? when followed by +/- offset (e.g., ?-232) but NOT when followed by _
    // (e.g., ?_-540 needs the complex parser for patterns like ?_-540_3117+?del)
    let use_fast_path = bytes[0].is_ascii_digit()
        || bytes[0] == b'*'
        || bytes[0] == b'-'
        || (bytes[0] == b'?' && bytes.len() > 1 && (bytes[1] == b'+' || bytes[1] == b'-'));
    if use_fast_path {
        let (remaining, start) = parse_cds_pos(input)?;
        // Check if this is a range (followed by _)
        if let Some(after_underscore) = remaining.strip_prefix('_') {
            // Only use fast path if followed by a position start character (simple range)
            // Fall through to complex parser for patterns like 100_(200)del
            let after_bytes = after_underscore.as_bytes();
            // Note: ? is NOT included - it needs the complex parser
            let is_simple_range = !after_bytes.is_empty()
                && (after_bytes[0].is_ascii_digit()
                    || after_bytes[0] == b'*'
                    || after_bytes[0] == b'-');
            if is_simple_range {
                let (remaining, end) = parse_cds_pos(after_underscore)?;
                // Reject inverted ranges
                if cds_pos_is_inverted(&start, &end) {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }
                return Ok((
                    remaining,
                    Interval::with_complex_boundaries(
                        UncertainBoundary::certain(start),
                        UncertainBoundary::certain(end),
                    ),
                ));
            }
            // Fall through to complex parser
        } else {
            // Single position (no underscore follows)
            return Ok((remaining, CdsInterval::point(start)));
        }
    }

    // Complex cases: starts with ( or ?
    alt((
        // Simple uncertain interval: (pos_pos) NOT followed by _
        // This produces (pos)_(pos) in output - both positions are uncertain
        parse_simple_uncertain_cds_interval,
        // Complex interval with range boundaries: (start_boundary)_(end_boundary)
        // This handles patterns like: (4185+1_4186-1)_(4357+1_4358-1)del or simple ranges
        |input| {
            let (remaining, (start, _, end)) =
                (parse_cds_boundary, tag("_"), parse_cds_boundary).parse(input)?;
            // For simple ranges with certain positions, reject inverted ranges
            if let (
                UncertainBoundary::Single(Mu::Certain(s)),
                UncertainBoundary::Single(Mu::Certain(e)),
            ) = (&start, &end)
            {
                if cds_pos_is_inverted(s, e) {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }
            }
            Ok((remaining, Interval::with_complex_boundaries(start, end)))
        },
        // Single position (possibly uncertain, unknown, or a range boundary)
        map(parse_cds_boundary, |boundary| match boundary {
            UncertainBoundary::Single(Mu::Certain(inner)) => CdsInterval::point(inner),
            UncertainBoundary::Single(Mu::Uncertain(inner)) => {
                Interval::with_uncertainty(Mu::uncertain(inner), Mu::uncertain(inner))
            }
            UncertainBoundary::Single(Mu::Unknown) => {
                Interval::with_uncertainty(Mu::Unknown, Mu::Unknown)
            }
            UncertainBoundary::Range { start, end } => {
                // A single range boundary used as a point - unusual but valid
                Interval::with_complex_boundaries(
                    UncertainBoundary::Range {
                        start: start.clone(),
                        end: end.clone(),
                    },
                    UncertainBoundary::Range { start, end },
                )
            }
        }),
    ))
    .parse(input)
}

/// Parse a transcript range boundary: (pos_pos)
fn parse_tx_range_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::TxPos>> {
    delimited(
        char('('),
        map((parse_tx_pos, tag("_"), parse_tx_pos), |(start, _, end)| {
            UncertainBoundary::range(Mu::certain(start), Mu::certain(end))
        }),
        char(')'),
    )
    .parse(input)
}

/// Parse a transcript boundary: (pos_pos), (pos), or pos
fn parse_tx_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::TxPos>> {
    alt((
        // Range boundary: (pos_pos)
        parse_tx_range_boundary,
        // Single uncertain position: (pos)
        map(
            delimited(char('('), parse_tx_pos, char(')')),
            UncertainBoundary::uncertain,
        ),
        // Certain position: pos
        map(parse_tx_pos, UncertainBoundary::certain),
    ))
    .parse(input)
}

fn parse_tx_interval(input: &str) -> IResult<&str, TxInterval> {
    alt((
        // Whole interval uncertain: (100_200) NOT followed by _
        |input| {
            let (remaining, (start, _, end)) =
                delimited(char('('), (parse_tx_pos, tag("_"), parse_tx_pos), char(')'))
                    .parse(input)?;
            // If followed by _, this is a complex boundary, not a simple uncertain interval
            if remaining.starts_with('_') {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            Ok((
                remaining,
                Interval::with_uncertainty(Mu::uncertain(start), Mu::uncertain(end)),
            ))
        },
        // Complex interval with range boundaries: (pos_pos)_(pos_pos)
        |input| {
            let (remaining, (start, _, end)) =
                (parse_tx_boundary, tag("_"), parse_tx_boundary).parse(input)?;
            Ok((remaining, Interval::with_complex_boundaries(start, end)))
        },
        // Range with individual uncertainty
        map(
            (parse_uncertain_tx_pos, tag("_"), parse_uncertain_tx_pos),
            |(start, _, end)| Interval::with_uncertainty(start, end),
        ),
        // Single position (possibly uncertain or unknown)
        map(parse_uncertain_tx_pos, |pos| match pos {
            Mu::Unknown => Interval::with_uncertainty(Mu::Unknown, Mu::Unknown),
            Mu::Uncertain(inner) => {
                Interval::with_uncertainty(Mu::uncertain(inner), Mu::uncertain(inner))
            }
            Mu::Certain(inner) => TxInterval::point(inner),
        }),
    ))
    .parse(input)
}

/// Parse a protein range boundary: (?_pos), (pos_?), or (pos_pos)
fn parse_prot_range_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::ProtPos>> {
    delimited(
        char('('),
        alt((
            // (?_pos) - unknown to known position
            map((tag("?"), tag("_"), parse_prot_pos), |(_, _, end)| {
                UncertainBoundary::range(Mu::Unknown, Mu::certain(end))
            }),
            // (pos_?) - known position to unknown
            map((parse_prot_pos, tag("_"), tag("?")), |(start, _, _)| {
                UncertainBoundary::range(Mu::certain(start), Mu::Unknown)
            }),
            // (pos_pos) - range with both positions known
            map(
                (parse_prot_pos, tag("_"), parse_prot_pos),
                |(start, _, end)| UncertainBoundary::range(Mu::certain(start), Mu::certain(end)),
            ),
        )),
        char(')'),
    )
    .parse(input)
}

/// Parse amino acid followed by position range: Met(?_1), Glu(1_?), or Glu2(?)
/// This handles patterns like p.Met(?_1)_Glu2(?) where the amino acid has an uncertain position range
fn parse_prot_aa_with_range(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::ProtPos>> {
    use crate::hgvs::location::ProtPos;
    use nom::character::complete::digit1;

    let (remaining, aa) = parse_amino_acid(input)?;

    // Check for AminoAcid + Number + (?) pattern: e.g., Glu2(?)
    if let Ok((number_remaining, num_str)) =
        digit1::<&str, nom::error::Error<&str>>.parse(remaining)
    {
        if number_remaining.starts_with("(?)") {
            let pos = num_str.parse::<u64>().unwrap_or(0);
            let (final_remaining, _) =
                tag::<&str, &str, nom::error::Error<&str>>("(?)").parse(number_remaining)?;
            return Ok((
                final_remaining,
                UncertainBoundary::uncertain(ProtPos::new(aa, pos)),
            ));
        }
    }

    // Must be followed by (
    if !remaining.starts_with('(') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    let (remaining, _) = char('(').parse(remaining)?;

    // Parse the range inside parens
    let (remaining, boundary) = alt((
        // (?_NUMBER) - unknown to known number (e.g., (?_1))
        map(
            (tag("?"), tag("_"), digit1),
            |(_, _, end): (&str, &str, &str)| {
                let pos = end.parse::<u64>().unwrap_or(0);
                UncertainBoundary::range(Mu::Unknown, Mu::certain(ProtPos::new(aa, pos)))
            },
        ),
        // (NUMBER_?) - known number to unknown (e.g., (1_?))
        map(
            (digit1, tag("_"), tag("?")),
            |(start, _, _): (&str, &str, &str)| {
                let pos = start.parse::<u64>().unwrap_or(0);
                UncertainBoundary::range(Mu::certain(ProtPos::new(aa, pos)), Mu::Unknown)
            },
        ),
        // (?) - fully uncertain position (no number before)
        map(tag("?"), |_| {
            UncertainBoundary::uncertain(ProtPos::new(aa, 0))
        }),
    ))
    .parse(remaining)?;

    let (remaining, _) = char(')').parse(remaining)?;

    Ok((remaining, boundary))
}

/// Parse a protein boundary: (?_pos), (pos_?), (pos_pos), (pos), ?, pos, or AminoAcid(?_N)
fn parse_prot_boundary(
    input: &str,
) -> IResult<&str, UncertainBoundary<crate::hgvs::location::ProtPos>> {
    alt((
        // Amino acid with position range: Met(?_1), Glu(1_?), Ter(?)
        // Must be checked BEFORE certain position to avoid consuming just "Met"
        parse_prot_aa_with_range,
        // Range boundary: (?_pos), (pos_?), or (pos_pos)
        parse_prot_range_boundary,
        // Single uncertain position: (pos)
        map(
            delimited(char('('), parse_prot_pos, char(')')),
            UncertainBoundary::uncertain,
        ),
        // Unknown amino acid with position: ?NUMBER (e.g., ?4 means unknown amino acid at position 4)
        map(preceded(char('?'), digit1), |n: &str| {
            UncertainBoundary::certain(ProtPos::new(AminoAcid::Xaa, n.parse().unwrap_or(0)))
        }),
        // Unknown: ?
        map(tag("?"), |_| UncertainBoundary::unknown()),
        // Certain position: pos
        map(parse_prot_pos, UncertainBoundary::certain),
    ))
    .parse(input)
}

fn parse_prot_interval(input: &str) -> IResult<&str, ProtInterval> {
    alt((
        // Simple uncertain interval: (pos_pos) NOT followed by _
        // This is for patterns like (Lys23_Leu24)del where the whole interval is uncertain
        |input| {
            let (remaining, (start, _, end)) = delimited(
                char('('),
                (parse_prot_pos, tag("_"), parse_prot_pos),
                char(')'),
            )
            .parse(input)?;
            // If followed by _, this is a complex boundary, not a simple uncertain interval
            if remaining.starts_with('_') {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            Ok((
                remaining,
                Interval::with_uncertainty(Mu::uncertain(start), Mu::uncertain(end)),
            ))
        },
        // Complex interval with range boundaries: (?_pos)_pos, pos_(pos_?), etc.
        |input| {
            let (remaining, (start, _, end)) =
                (parse_prot_boundary, tag("_"), parse_prot_boundary).parse(input)?;
            Ok((remaining, Interval::with_complex_boundaries(start, end)))
        },
        // Single position (possibly uncertain, unknown, or a range boundary)
        map(parse_prot_boundary, |boundary| match boundary {
            UncertainBoundary::Single(Mu::Certain(inner)) => ProtInterval::point(inner),
            UncertainBoundary::Single(Mu::Uncertain(inner)) => {
                Interval::with_uncertainty(Mu::uncertain(inner), Mu::uncertain(inner))
            }
            UncertainBoundary::Single(Mu::Unknown) => {
                Interval::with_uncertainty(Mu::Unknown, Mu::Unknown)
            }
            UncertainBoundary::Range { start, end } => {
                // A single range boundary used as a point - unusual but valid
                Interval::with_complex_boundaries(
                    UncertainBoundary::Range {
                        start: start.clone(),
                        end: end.clone(),
                    },
                    UncertainBoundary::Range { start, end },
                )
            }
        }),
    ))
    .parse(input)
}

fn parse_rna_interval(input: &str) -> IResult<&str, RnaInterval> {
    alt((
        // Whole interval uncertain: (100_200)
        map(
            delimited(
                char('('),
                (parse_rna_pos, tag("_"), parse_rna_pos),
                char(')'),
            ),
            |(start, _, end)| Interval::with_uncertainty(Mu::uncertain(start), Mu::uncertain(end)),
        ),
        // Range with individual uncertainty
        map(
            (parse_uncertain_rna_pos, tag("_"), parse_uncertain_rna_pos),
            |(start, _, end)| Interval::with_uncertainty(start, end),
        ),
        // Single position (possibly uncertain or unknown)
        map(parse_uncertain_rna_pos, |pos| match pos {
            Mu::Unknown => Interval::with_uncertainty(Mu::Unknown, Mu::Unknown),
            Mu::Uncertain(inner) => {
                Interval::with_uncertainty(Mu::uncertain(inner), Mu::uncertain(inner))
            }
            Mu::Certain(inner) => RnaInterval::point(inner),
        }),
    ))
    .parse(input)
}

/// Parse genomic variant (g.)
fn parse_genome_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("g.").parse(input)?;

        // First try whole-genome identity (g.=) - no position
        if let Ok((remaining, edit)) = parse_whole_genome_identity(input) {
            let dummy_pos = crate::hgvs::location::GenomePos::new(1);
            let dummy_interval = GenomeInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Genome(GenomeVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try whole-genome unknown (g.?) - no position
        if let Ok((remaining, edit)) = parse_whole_genome_unknown(input) {
            let dummy_pos = crate::hgvs::location::GenomePos::new(1);
            let dummy_interval = GenomeInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Genome(GenomeVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try trans-allele compact-prefix shorthand: g.[edit1];[edit2]
        // Detection mirrors the CDS/RNA paths (parse_cds_allele_shorthand,
        // parse_rna_allele_shorthand): starts with `[` and contains `];[`.
        if input.starts_with('[') && input.contains("];[") {
            if let Ok((remaining, variant)) =
                parse_genome_trans_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, variant));
            }
        }

        // Try compound allele notation: g.[pos1edit1;pos2edit2;...] or g.[a(;)b]
        if input.starts_with('[') {
            if let Ok((remaining, allele)) =
                parse_genome_compound_allele(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, HgvsVariant::Allele(allele)));
            }
        }

        // Bracketless unknown-phase shorthand: g.123G>A(;)345del (#123)
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_genome_position_unknown_phase(
                input,
                accession.clone(),
                gene_symbol.clone(),
                GenomeKind::Genome,
            );
        }

        let (input, interval) = parse_genome_interval(input)?;

        // Try to parse an edit; if no edit found, use position-only identity
        let (input, edit) = if let Ok((remaining, edit)) = parse_na_edit(input) {
            (remaining, edit)
        } else if input.is_empty() || input.starts_with(']') || input.starts_with(';') {
            // Position-only pattern (e.g., g.12345 or g.100_200)
            // Use identity with no sequence to represent "position reference"
            (
                input,
                crate::hgvs::edit::NaEdit::Identity {
                    sequence: None,
                    whole_entity: false,
                },
            )
        } else {
            // Unknown pattern - fail
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Tag,
            )));
        };

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

/// Tag that selects which DNA variant constructor to use when the genome-style
/// allele helpers are shared between `g.`, `m.`, and `o.`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum GenomeKind {
    Genome,
    Mt,
    Circular,
}

impl GenomeKind {
    fn build_variant(
        self,
        accession: Accession,
        gene_symbol: Option<String>,
        interval: GenomeInterval,
        edit: crate::hgvs::edit::NaEdit,
    ) -> HgvsVariant {
        match self {
            GenomeKind::Genome => HgvsVariant::Genome(GenomeVariant {
                accession,
                gene_symbol,
                loc_edit: LocEdit::new(interval, edit),
            }),
            GenomeKind::Mt => HgvsVariant::Mt(MtVariant {
                accession,
                gene_symbol,
                loc_edit: LocEdit::new(interval, edit),
            }),
            GenomeKind::Circular => HgvsVariant::Circular(CircularVariant {
                accession,
                gene_symbol,
                loc_edit: LocEdit::new(interval, edit),
            }),
        }
    }
}

/// Find the index of the `]` that closes the leading `[` in `input`, scanning
/// at bracket depth 0. Returns `None` if `input` does not start with `[` or if
/// the bracket is unbalanced.
///
/// Plain `input.find(']')` would truncate at any inner edit bracket
/// (`delins[ACC:g.x_y]`, `delins[A;T]`, etc.); plain `input.rfind(']')` would
/// over-consume on trans-form `[a];[b]`. The depth-tracking scan handles both.
fn find_top_level_close_bracket(input: &str) -> Option<usize> {
    if !input.starts_with('[') {
        return None;
    }
    let mut depth: i32 = 0;
    for (i, b) in input.bytes().enumerate() {
        match b {
            b'[' => depth += 1,
            b']' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Parse a compound allele with genomic variants:
///   `[pos1edit1;pos2edit2;...]`   (cis)
///   `[pos1edit1(;)pos2edit2;...]` (unknown phase)
///
/// A single bracket pair must use exactly one separator type; mixed
/// `;`/`(;)` inside one bracket pair is not spec-valid and is rejected.
fn parse_genome_compound_allele(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, AlleleVariant> {
    parse_genome_kind_compound_allele(input, accession, gene_symbol, GenomeKind::Genome)
}

fn parse_genome_kind_compound_allele(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
    kind: GenomeKind,
) -> IResult<&str, AlleleVariant> {
    if !input.starts_with('[') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Locate the `]` that closes the leading `[`, scanning at bracket depth 0
    // so that members containing nested edit brackets (`delins[ACC:g.x_y]`,
    // `delins[A;T]`, etc.) are not truncated at the inner `]`.
    let close_bracket = find_top_level_close_bracket(input).ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;

    let content = &input[1..close_bracket];
    let remaining = &input[close_bracket + 1..];

    // Distinguish unknown phase from cis based on `(;)` presence.
    let has_unknown_phase = content.contains("(;)");
    let has_cis_separator = {
        // Any `;` that isn't part of `(;)`.
        let temp = content.replace("(;)", "\x00");
        temp.contains(';')
    };

    // Mixed `;` and `(;)` inside a single bracket pair is not spec-valid
    // (HGVS `recommendations/{DNA,protein}/alleles.md` only mixes `;`/`(;)` at
    // the top level via `[a;b];[c](;)d`, not inside one `[...]`). Reject
    // rather than silently flatten the cis subgroup boundary into a single
    // `phase: Unknown` allele.
    if has_unknown_phase && has_cis_separator {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    let phase = if has_unknown_phase {
        AllelePhase::Unknown
    } else {
        AllelePhase::Cis
    };

    let separator = if has_unknown_phase { "(;)" } else { ";" };
    let mut variants = Vec::with_capacity(4);

    for part in content.split(separator) {
        let part = part.trim();
        if part.is_empty() {
            // Empty parts (e.g. `[a;;b]`, `[a(;)(;)b]`, or trailing `[a(;)]`)
            // are malformed; reject rather than silently dropping them.
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }
        let (edit_remaining, interval) = parse_genome_interval(part)?;
        let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
            (r, e)
        } else {
            (
                edit_remaining,
                crate::hgvs::edit::NaEdit::Identity {
                    sequence: None,
                    whole_entity: false,
                },
            )
        };
        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }
        variants.push(kind.build_variant(accession.clone(), gene_symbol.clone(), interval, edit));
    }

    // Singletons (`[a]`) are intentionally accepted by ferro: the bracketed
    // wrapper is preserved for upstream tooling rather than rejected, and a
    // non-empty `remaining` (e.g. trans-form `[a];[b]`) is handled by the
    // outer parser. See `test_singleton_cis_allele_preserves_wrapper` and
    // `pinned_v21_normalization_behavior` for the pinned behavior.
    if variants.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    Ok((remaining, AlleleVariant::new(variants, phase)))
}

/// Parse position-based unknown-phase shorthand for genome-style coord systems:
///   `123G>A(;)345del` (uses [`GenomeKind`] to select the wrapping variant kind)
fn parse_genome_position_unknown_phase(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
    kind: GenomeKind,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(4);

    for part in input.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            // An empty `(;)` group (e.g. `a(;)(;)b` or trailing/leading
            // `(;)`) is malformed; reject rather than silently dropping it.
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        let (edit_remaining, interval) = parse_genome_interval(part)?;
        let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }

        variants.push(kind.build_variant(accession.clone(), gene_symbol.clone(), interval, edit));
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        "",
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Unknown)),
    ))
}

/// Parse a genomic trans-allele compact-prefix shorthand: `[edit1];[edit2]`
/// (with the `g.` already consumed by the caller). Each bracketed group holds
/// a single sub-variant rendered with this allele's accession. Mirrors
/// `parse_cds_trans_allele_shorthand` and `parse_rna_trans_allele_shorthand`.
fn parse_genome_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = remaining[1..close_bracket].trim();

        let variant = if content == "0" {
            HgvsVariant::NullAllele
        } else if content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_genome_interval(content)?;
            // Edit is optional - if not present, treat as identity (position-only).
            let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                (r, e)
            } else {
                (
                    edit_remaining,
                    crate::hgvs::edit::NaEdit::Identity {
                        sequence: None,
                        whole_entity: false,
                    },
                )
            };

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Genome(GenomeVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse whole-genome identity: g.=
fn parse_whole_genome_identity(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    map(tag("="), |_| {
        crate::hgvs::edit::NaEdit::whole_entity_identity()
    })
    .parse(input)
}

/// Parse whole-genome unknown: g.?
fn parse_whole_genome_unknown(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    // Only match terminal ? (not ? followed by _ which indicates uncertain position)
    let (remaining, _) = tag("?").parse(input)?;
    if remaining.starts_with('_') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }
    Ok((remaining, crate::hgvs::edit::NaEdit::whole_entity_unknown()))
}

/// Parse whole-CDS identity: c.=
fn parse_whole_cds_identity(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    map(tag("="), |_| {
        crate::hgvs::edit::NaEdit::whole_entity_identity()
    })
    .parse(input)
}

/// Parse whole-CDS unknown: c.?
/// Only matches if ? is at end (not followed by _, +, -, or edit keywords like dup/del/ins)
fn parse_whole_cds_unknown(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    let (remaining, _) = tag("?").parse(input)?;
    // If followed by '_', this is an interval with unknown start, not whole entity unknown
    // If followed by '+' or '-', this has an offset (e.g., ?-232)
    // If followed by edit keywords, it's an unknown position with edit (e.g., ?dup)
    if remaining.starts_with('_')
        || remaining.starts_with('+')
        || remaining.starts_with('-')
        || remaining.starts_with("dup")
        || remaining.starts_with("del")
        || remaining.starts_with("ins")
        || remaining.starts_with("inv")
    {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }
    Ok((remaining, crate::hgvs::edit::NaEdit::whole_entity_unknown()))
}

/// Parse CDS variant (c.)
fn parse_cds_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("c.").parse(input)?;

        // Check for cis allele shorthand: c.[145C>T;147C>G]
        if input.starts_with('[') {
            return parse_cds_allele_shorthand(input, accession.clone(), gene_symbol.clone());
        }

        // Check for position-based unknown phase shorthand: c.2376G>C(;)3103del
        // The (;) separator indicates unknown phase between variants
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_cds_position_unknown_phase(input, accession.clone(), gene_symbol.clone());
        }

        // First try whole-CDS identity (c.=) - no position
        if let Ok((remaining, edit)) = parse_whole_cds_identity(input) {
            // Use a dummy interval for whole-entity identity
            let dummy_pos = crate::hgvs::location::CdsPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = CdsInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Cds(CdsVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try whole-CDS unknown (c.?) - no position
        if let Ok((remaining, edit)) = parse_whole_cds_unknown(input) {
            // Use a dummy interval for whole-entity unknown
            let dummy_pos = crate::hgvs::location::CdsPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = CdsInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Cds(CdsVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try predicted variant: c.(positionEdit) where the whole position+edit is in parens
        // e.g., c.(9740C>A) or c.(742G>A)
        if input.starts_with('(') && !input.starts_with("(?") {
            // Check if this is a predicted variant pattern (simple position+edit in parens)
            // vs an uncertain interval like (100_200)
            if let Some(close_paren) = input.find(')') {
                let inner = &input[1..close_paren];
                // If inner contains a simple substitution pattern (no underscore for range)
                // and doesn't start with a digit followed by underscore, it's likely a predicted variant
                if inner.contains('>') && !inner.contains('_') {
                    // Parse the inner content as position + edit
                    if let Ok((after_edit, interval)) = parse_cds_interval(inner) {
                        if let Ok((remaining_inner, edit)) = parse_na_edit(after_edit) {
                            if remaining_inner.is_empty() {
                                // Mark as predicted by wrapping in uncertainty
                                let remaining = &input[close_paren + 1..];
                                return Ok((
                                    remaining,
                                    HgvsVariant::Cds(CdsVariant {
                                        accession: accession.clone(),
                                        gene_symbol: gene_symbol.clone(),
                                        loc_edit: LocEdit::new_predicted(interval, edit),
                                    }),
                                ));
                            }
                        }
                    }
                }
            }
        }

        let (input, interval) = parse_cds_interval(input)?;

        // Try to parse an edit - if none found, check if position-only is allowed
        let (input, edit) = if let Ok((remaining, edit)) = parse_na_edit(input) {
            (remaining, edit)
        } else if input.is_empty() || !input.chars().next().unwrap_or(' ').is_alphanumeric() {
            // No edit found - position-only is only allowed for:
            // 1. Ranges (different start and end positions)
            // 2. UTR positions (3' or 5' UTR)
            let is_range = match (&interval.start, &interval.end) {
                (
                    crate::hgvs::interval::UncertainBoundary::Single(
                        crate::hgvs::uncertainty::Mu::Certain(start),
                    ),
                    crate::hgvs::interval::UncertainBoundary::Single(
                        crate::hgvs::uncertainty::Mu::Certain(end),
                    ),
                ) => start != end,
                _ => true, // Complex boundaries count as ranges
            };

            let is_utr = match &interval.start {
                crate::hgvs::interval::UncertainBoundary::Single(
                    crate::hgvs::uncertainty::Mu::Certain(pos),
                ) => pos.utr3 || pos.base < 0, // 3' UTR or 5' UTR
                _ => false,
            };

            if is_range || is_utr {
                (input, crate::hgvs::edit::NaEdit::PositionOnly)
            } else {
                // Simple single position without edit - reject it
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Tag,
                )));
            }
        } else {
            // There's more input but it doesn't parse as an edit - this is an error
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Tag,
            )));
        };

        Ok((
            input,
            HgvsVariant::Cds(CdsVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse position-based unknown phase shorthand: 2376G>C(;)3103del
fn parse_cds_position_unknown_phase(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Pre-allocate with estimated capacity (most alleles have 2-4 variants)
    let mut variants = Vec::with_capacity(4);

    // Split by (;) and parse each part
    for part in input.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        // Parse interval + edit
        let (edit_remaining, interval) = parse_cds_interval(part)?;
        let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }

        variants.push(HgvsVariant::Cds(CdsVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }));
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        "",
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Unknown)),
    ))
}

/// Parse CDS allele shorthand: [145C>T;147C>G], [145C>T(;)147C>G], or [76A>C];[0]
/// Also handles mixed phase: [123A>G;456C>T(;)789G>A] where some variants are cis
/// and others have unknown phase relationship.
fn parse_cds_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Must start with [
    if !input.starts_with('[') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Check for trans allele pattern: [var];[var] or [var];[0] or [var];[?]
    if input.contains("];[") {
        return parse_cds_trans_allele_shorthand(input, accession, gene_symbol);
    }

    let close_bracket = input.rfind(']').ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;

    let content = &input[1..close_bracket];
    let remaining = &input[close_bracket + 1..];

    // Check for mixed phase: contains both ; and (;)
    // We need to check for ; that's NOT part of (;)
    let has_unknown_phase = content.contains("(;)");
    let has_cis_separator = {
        // Replace (;) temporarily to check for standalone ;
        let temp = content.replace("(;)", "\x00");
        temp.contains(';')
    };

    // Determine phase and parsing strategy
    let phase = if has_unknown_phase {
        // If there's any unknown phase, the overall phase is unknown
        AllelePhase::Unknown
    } else {
        AllelePhase::Cis
    };

    // Parse variants - handle mixed separators
    // Pre-allocate with estimated capacity (most alleles have 2-4 variants)
    let mut variants = Vec::with_capacity(4);

    if has_unknown_phase && has_cis_separator {
        // Mixed phase: split on (;) first, then on ;
        for unknown_group in content.split("(;)") {
            for part in unknown_group.split(';') {
                let part = part.trim();
                if part.is_empty() {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }

                let (edit_remaining, interval) = parse_cds_interval(part)?;
                // Edit is optional - if not present, treat as identity (no change)
                let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                    (r, e)
                } else {
                    (
                        edit_remaining,
                        crate::hgvs::edit::NaEdit::Identity {
                            sequence: None,
                            whole_entity: false,
                        },
                    )
                };

                if !final_remaining.trim().is_empty() {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        final_remaining,
                        nom::error::ErrorKind::Tag,
                    )));
                }

                variants.push(HgvsVariant::Cds(CdsVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(interval, edit),
                }));
            }
        }
    } else {
        // Single separator type
        let separator = if has_unknown_phase { "(;)" } else { ";" };

        for part in content.split(separator) {
            let part = part.trim();
            if part.is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }

            // Parse interval + edit (e.g., "145C>T" or "100_200del")
            let (edit_remaining, interval) = parse_cds_interval(part)?;
            // Edit is optional - if not present, treat as identity (no change)
            let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                (r, e)
            } else {
                (
                    edit_remaining,
                    crate::hgvs::edit::NaEdit::Identity {
                        sequence: None,
                        whole_entity: false,
                    },
                )
            };

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            variants.push(HgvsVariant::Cds(CdsVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }));
        }
    }

    if variants.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, phase)),
    ))
}

/// Parse CDS trans allele shorthand: [76A>C];[0], [76A>C];[?], [var1];[var2]
fn parse_cds_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Pre-allocate with capacity for trans alleles (typically 2)
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        // Must start with [
        if !remaining.starts_with('[') {
            break;
        }

        // Find closing bracket
        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = &remaining[1..close_bracket].trim();

        // Check for special markers
        let variant = if *content == "0" {
            HgvsVariant::NullAllele
        } else if *content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            // Parse as CDS variant (interval + edit)
            let (edit_remaining, interval) = parse_cds_interval(content)?;
            let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Cds(CdsVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        // Check for more variants (semicolon separator)
        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse transcript variant (n.)
fn parse_tx_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("n.").parse(input)?;

        // Compact-prefix trans-allele shorthand: n.[a];[b]. Mirrors
        // parse_genome_variant's dispatch added in PR #146; the expanded
        // form [ACC:n.a];[ACC:n.b] is handled by the top-level allele parser.
        if input.starts_with('[') && input.contains("];[") {
            if let Ok((remaining, variant)) =
                parse_tx_trans_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, variant));
            }
        }

        // Bracketed compound allele: n.[var;var;...] or n.[var(;)var]
        if input.starts_with('[') {
            if let Ok((remaining, allele)) =
                parse_tx_compound_allele(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, HgvsVariant::Allele(allele)));
            }
        }

        // Bracketless unknown-phase shorthand: n.100A>G(;)200T>C (#123)
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_tx_position_unknown_phase(input, accession.clone(), gene_symbol.clone());
        }

        let (input, interval) = parse_tx_interval(input)?;
        let (input, edit) = parse_na_edit(input)?;

        Ok((
            input,
            HgvsVariant::Tx(TxVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse a non-coding transcript trans-allele compact-prefix shorthand:
/// `[edit1];[edit2]` (with the `n.` already consumed by the caller). Each
/// bracketed group holds a single sub-variant rendered with this allele's
/// accession. Mirrors `parse_genome_trans_allele_shorthand`.
fn parse_tx_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = remaining[1..close_bracket].trim();

        let variant = if content == "0" {
            HgvsVariant::NullAllele
        } else if content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_tx_interval(content)?;
            // Edit is optional - if not present, treat as identity (position-only),
            // matching parse_genome_trans_allele_shorthand.
            let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                (r, e)
            } else {
                (
                    edit_remaining,
                    crate::hgvs::edit::NaEdit::Identity {
                        sequence: None,
                        whole_entity: false,
                    },
                )
            };

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Tx(TxVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse a compound allele with `n.` (transcript) variants:
///   `[100A>G;200T>C]` (cis) or `[100A>G(;)200T>C]` (unknown phase)
fn parse_tx_compound_allele(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, AlleleVariant> {
    if !input.starts_with('[') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // See `find_top_level_close_bracket` for why a depth-aware scan is used.
    let close_bracket = find_top_level_close_bracket(input).ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;

    let content = &input[1..close_bracket];
    let remaining = &input[close_bracket + 1..];

    let has_unknown_phase = content.contains("(;)");
    let has_cis_separator = {
        let temp = content.replace("(;)", "\x00");
        temp.contains(';')
    };

    // Mixed `;`/`(;)` inside one bracket pair is not spec-valid — see
    // `parse_genome_kind_compound_allele` for the spec citation.
    if has_unknown_phase && has_cis_separator {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    let phase = if has_unknown_phase {
        AllelePhase::Unknown
    } else {
        AllelePhase::Cis
    };

    let separator = if has_unknown_phase { "(;)" } else { ";" };

    let mut variants = Vec::with_capacity(4);
    for part in content.split(separator) {
        let part = part.trim();
        if part.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }
        let (edit_remaining, interval) = parse_tx_interval(part)?;
        let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
            (r, e)
        } else {
            (
                edit_remaining,
                crate::hgvs::edit::NaEdit::Identity {
                    sequence: None,
                    whole_entity: false,
                },
            )
        };
        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }
        variants.push(HgvsVariant::Tx(TxVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }));
    }

    // Singletons are intentionally accepted — see
    // `parse_genome_kind_compound_allele` for the rationale.
    if variants.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    Ok((remaining, AlleleVariant::new(variants, phase)))
}

/// Parse position-based unknown-phase shorthand for `n.`:
///   `100A>G(;)200T>C`
fn parse_tx_position_unknown_phase(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(4);

    for part in input.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }
        let (edit_remaining, interval) = parse_tx_interval(part)?;
        let (final_remaining, edit) = parse_na_edit(edit_remaining)?;
        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }
        variants.push(HgvsVariant::Tx(TxVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }));
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        "",
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Unknown)),
    ))
}

/// Parse mitochondrial variant (m.)
fn parse_mt_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("m.").parse(input)?;

        // Compact-prefix trans-allele shorthand: m.[a];[b]. Mirrors
        // parse_genome_variant's dispatch added in PR #146.
        if input.starts_with('[') && input.contains("];[") {
            if let Ok((remaining, variant)) =
                parse_mt_trans_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, variant));
            }
        }

        // Bracketed compound allele: m.[var;var] or m.[var(;)var]
        if input.starts_with('[') {
            if let Ok((remaining, allele)) = parse_genome_kind_compound_allele(
                input,
                accession.clone(),
                gene_symbol.clone(),
                GenomeKind::Mt,
            ) {
                return Ok((remaining, HgvsVariant::Allele(allele)));
            }
        }

        // Bracketless unknown-phase shorthand: m.100A>G(;)200T>C (#123)
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_genome_position_unknown_phase(
                input,
                accession.clone(),
                gene_symbol.clone(),
                GenomeKind::Mt,
            );
        }

        let (input, interval) = parse_genome_interval(input)?;
        let (input, edit) = parse_na_edit(input)?;

        Ok((
            input,
            HgvsVariant::Mt(MtVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse a mitochondrial trans-allele compact-prefix shorthand:
/// `[edit1];[edit2]` (with the `m.` already consumed). Mirrors
/// `parse_genome_trans_allele_shorthand`; mitochondrial variants reuse
/// `parse_genome_interval`.
fn parse_mt_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = remaining[1..close_bracket].trim();

        let variant = if content == "0" {
            HgvsVariant::NullAllele
        } else if content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_genome_interval(content)?;
            let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                (r, e)
            } else {
                (
                    edit_remaining,
                    crate::hgvs::edit::NaEdit::Identity {
                        sequence: None,
                        whole_entity: false,
                    },
                )
            };

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Mt(MtVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse whole-protein identity: p.= or p.(=)
fn parse_whole_protein_identity(input: &str) -> IResult<&str, ProteinEdit> {
    alt((
        // Predicted identity: (=)
        map(tag("(=)"), |_| {
            ProteinEdit::whole_protein_identity_predicted()
        }),
        // Certain identity: =
        map(tag("="), |_| ProteinEdit::whole_protein_identity()),
    ))
    .parse(input)
}

/// Parse no protein production: p.0 or p.0?
fn parse_whole_protein_no_protein(input: &str) -> IResult<&str, ProteinEdit> {
    alt((
        // Predicted no-protein: 0?
        map(tag("0?"), |_| ProteinEdit::no_protein_predicted()),
        // Certain no-protein: 0
        map(tag("0"), |_| ProteinEdit::no_protein()),
    ))
    .parse(input)
}

/// Parse whole-protein unknown: p.? or p.(?)
fn parse_whole_protein_unknown(input: &str) -> IResult<&str, ProteinEdit> {
    alt((
        // Predicted unknown: (?)
        map(tag("(?)"), |_| {
            ProteinEdit::whole_protein_unknown_predicted()
        }),
        // Certain unknown: ?
        map(tag("?"), |_| ProteinEdit::whole_protein_unknown()),
    ))
    .parse(input)
}

/// Parse a protein allele shorthand:
///   `p.[edit1;edit2;...]`     (cis)
///   `p.[edit1(;)edit2;...]`   (unknown phase)
///
/// A single bracket pair must use exactly one separator type; mixed
/// `;`/`(;)` inside one bracket pair is not spec-valid and is rejected.
fn parse_protein_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, AlleleVariant> {
    if !input.starts_with('[') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Fast path: any `(;)` inside the brackets means unknown phase. Slice the
    // bracketed content, split on `(;)`, and parse each sub-variant as
    // `interval+edit`. Use a depth-aware scan for the closing `]` so members
    // containing nested edit brackets are not truncated — see
    // `find_top_level_close_bracket`.
    let close_bracket = find_top_level_close_bracket(input).ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;
    let content = &input[1..close_bracket];
    let after_bracket = &input[close_bracket + 1..];

    let has_unknown_phase = content.contains("(;)");

    if has_unknown_phase {
        let has_cis_separator = {
            let temp = content.replace("(;)", "\x00");
            temp.contains(';')
        };
        // Mixed `;`/`(;)` inside one bracket pair is not spec-valid — see
        // `parse_genome_kind_compound_allele` for the spec citation.
        if has_cis_separator {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        let mut variants = Vec::with_capacity(4);
        for part in content.split("(;)") {
            let part = part.trim();
            if part.is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }
            let (edit_remaining, interval) = parse_prot_interval(part)?;
            let (final_remaining, edit) = parse_protein_edit(edit_remaining)?;
            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }
            variants.push(HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }));
        }

        // Singletons are intentionally accepted — see
        // `parse_genome_kind_compound_allele` for the rationale.
        if variants.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        return Ok((
            after_bracket,
            AlleleVariant::new(variants, AllelePhase::Unknown),
        ));
    }

    // Cis path (existing behavior).
    let (remaining, _) = char('[').parse(input)?;

    let mut variants = Vec::new();
    let mut current = remaining;

    loop {
        // Parse interval and edit
        let (rest, interval) = parse_prot_interval(current)?;
        let (rest, edit) = parse_protein_edit(rest)?;

        variants.push(HgvsVariant::Protein(ProteinVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }));

        // Check for more variants (semicolon separator) or end of allele
        if let Some(after_semi) = rest.strip_prefix(';') {
            current = after_semi;
        } else if let Some(after_bracket) = rest.strip_prefix(']') {
            current = after_bracket;
            break;
        } else {
            return Err(nom::Err::Error(nom::error::Error::new(
                rest,
                nom::error::ErrorKind::Tag,
            )));
        }
    }

    // Singletons are intentionally accepted — see
    // `parse_genome_kind_compound_allele` for the rationale.
    if variants.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    Ok((current, AlleleVariant::cis(variants)))
}

/// Parse a protein trans-allele compact-prefix shorthand:
/// `[edit1];[edit2]` (with `p.` already consumed by the caller). Each
/// bracketed group holds a single sub-variant. Mirrors
/// `parse_genome_trans_allele_shorthand`, but parses protein intervals +
/// edits and does NOT allow a bare-position (Identity) fallback — the
/// protein grammar requires an edit.
fn parse_protein_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = remaining[1..close_bracket].trim();

        let variant = if content == "0" {
            HgvsVariant::NullAllele
        } else if content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_prot_interval(content)?;
            let (final_remaining, edit) = parse_protein_edit(edit_remaining)?;

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse position-based unknown-phase shorthand for protein (#123):
///   `(Ser68Arg)(;)(Asn594del)`
///
/// Per `recommendations/protein/alleles.md` line 48, the protein unknown-phase
/// form does NOT use surrounding square brackets and each sub-variant is a
/// predicted change wrapped in `()`.
fn parse_protein_position_unknown_phase(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(4);

    for part in input.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        // Each part must be a parenthesized predicted change `(interval+edit)`.
        let (rest, (interval, edit)) = delimited(
            char('('),
            (parse_prot_interval, parse_protein_edit),
            char(')'),
        )
        .parse(part)?;

        if !rest.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                rest,
                nom::error::ErrorKind::Tag,
            )));
        }

        variants.push(HgvsVariant::Protein(ProteinVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::with_uncertainty(interval, Mu::Uncertain(edit)),
        }));
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        "",
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Unknown)),
    ))
}

/// Parse a numeric-only protein repeat (e.g., p.223PA[3], p.179_180AP[9])
/// These patterns have a numeric position (no amino acid) followed by single-letter AA repeat
fn parse_protein_numeric_repeat(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Parse the start position (just a number)
    let (remaining, start_num) = digit1.parse(input)?;
    let start: u64 = start_num.parse().map_err(|_| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Digit))
    })?;

    // Check for range (pos_pos)
    let (remaining, end_opt) = if remaining.starts_with('_') {
        let (rest, _) = tag("_").parse(remaining)?;
        let (rest, end_num) = digit1.parse(rest)?;
        let end: u64 = end_num.parse().map_err(|_| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Digit,
            ))
        })?;
        (rest, Some(end))
    } else {
        (remaining, None)
    };

    // Parse the protein repeat edit (single-letter AAs followed by [count])
    let (remaining, edit) = parse_protein_edit(remaining)?;

    // Verify this is actually a repeat edit (single or multi)
    if !matches!(
        edit,
        ProteinEdit::Repeat { .. } | ProteinEdit::MultiRepeat { .. }
    ) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    // Create protein positions using a placeholder amino acid (the actual AA is in the edit)
    let start_pos = ProtPos::new(AminoAcid::Xaa, start);
    let interval = match end_opt {
        Some(end) => {
            let end_pos = ProtPos::new(AminoAcid::Xaa, end);
            ProtInterval::new(start_pos, end_pos)
        }
        None => ProtInterval::point(start_pos),
    };

    Ok((
        remaining,
        HgvsVariant::Protein(ProteinVariant {
            accession,
            gene_symbol,
            loc_edit: LocEdit::new(interval, edit),
        }),
    ))
}

/// Parse numeric-only protein position (e.g., p.78, p.4894Q, p.42_43insAspAla)
/// These are non-standard notations that appear in ClinVar
/// - p.78 = position 78, unknown effect
/// - p.4894Q = position 4894, substitution to Gln (single-letter code)
/// - p.42_43insAspAla = insertion at positions 42-43
fn parse_protein_numeric_position(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Parse the start position number
    let (remaining, start_num) = digit1.parse(input)?;
    let start: u64 = start_num.parse().map_err(|_| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Digit))
    })?;

    if start == 0 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    }

    // Check for range (e.g., 42_43)
    let (remaining, end_opt) = if remaining.starts_with('_') {
        let (rest, _) = tag("_").parse(remaining)?;
        let (rest, end_num) = digit1.parse(rest)?;
        let end: u64 = end_num.parse().map_err(|_| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Digit,
            ))
        })?;
        (rest, Some(end))
    } else {
        (remaining, None)
    };

    // Create the interval
    let start_pos = ProtPos::new(AminoAcid::Xaa, start);
    let interval = match end_opt {
        Some(end) => {
            let end_pos = ProtPos::new(AminoAcid::Xaa, end);
            ProtInterval::new(start_pos, end_pos)
        }
        None => ProtInterval::point(start_pos),
    };

    // Check for edit (ins, del, dup) or single letter amino acid
    let (remaining, edit) = if remaining.starts_with("ins")
        || remaining.starts_with("del")
        || remaining.starts_with("dup")
    {
        // Parse the protein edit
        parse_protein_edit(remaining)?
    } else if remaining.starts_with(|c: char| c.is_ascii_uppercase()) {
        // Try to parse a single-letter amino acid
        let aa_char = remaining.chars().next().unwrap();
        if let Some(aa) = AminoAcid::from_one_letter(aa_char) {
            // This is a substitution to the given amino acid
            // We use Xaa as the reference since we don't know the original
            (
                &remaining[1..],
                ProteinEdit::Substitution {
                    reference: AminoAcid::Xaa,
                    alternative: aa,
                },
            )
        } else {
            // Not a valid amino acid letter - reject
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }
    } else if remaining.is_empty() || remaining.starts_with(' ') || remaining.starts_with(',') {
        // Just a position, no amino acid - treat as position-only unknown
        (remaining, ProteinEdit::position_unknown())
    } else {
        // Something else follows - reject and let other parsers try
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Verify,
        )));
    };

    Ok((
        remaining,
        HgvsVariant::Protein(ProteinVariant {
            accession,
            gene_symbol,
            loc_edit: LocEdit::new(interval, edit),
        }),
    ))
}

/// Parse protein variant (p.)
fn parse_protein_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("p.").parse(input)?;

        // First try whole-protein identity (p.= or p.(=)) - no position
        if let Ok((remaining, edit)) = parse_whole_protein_identity(input) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Protein(ProteinVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try no protein production (p.0 or p.0?) - no position
        if let Ok((remaining, edit)) = parse_whole_protein_no_protein(input) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Protein(ProteinVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try whole-protein unknown (p.?) - no position
        if let Ok((remaining, edit)) = parse_whole_protein_unknown(input) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Protein(ProteinVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try protein trans-allele compact-prefix shorthand: p.[edit1];[edit2]
        // before the cis allele path, since trans is the more specific shape.
        // Mirrors the DNA/RNA dispatches (parse_genome_variant,
        // parse_cds_variant, parse_rna_variant) and PR #146's fix for `g.`.
        if input.starts_with('[') && input.contains("];[") {
            if let Ok((remaining, variant)) =
                parse_protein_trans_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, variant));
            }
        }

        // Try protein allele: p.[edit1;edit2;...] or p.[edit1(;)edit2]
        if input.starts_with('[') {
            if let Ok((remaining, allele)) =
                parse_protein_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, HgvsVariant::Allele(allele)));
            }
        }

        // Bracketless unknown-phase shorthand for protein (#123):
        //   p.(Ser68Arg)(;)(Asn594del)
        // Per spec the protein form is bare (no surrounding `[]`). Each
        // sub-variant is a predicted change in parentheses.
        if input.starts_with('(') && input.contains(")(;)(") {
            return parse_protein_position_unknown_phase(
                input,
                accession.clone(),
                gene_symbol.clone(),
            );
        }

        // Try predicted protein change: p.(position+edit) - wrapped in parentheses
        if input.starts_with('(') && !input.starts_with("(=)") {
            // Check for predicted change pattern
            if let Ok((remaining, (interval, edit))) = delimited(
                char('('),
                (parse_prot_interval, parse_protein_edit),
                char(')'),
            )
            .parse(input)
            {
                return Ok((
                    remaining,
                    HgvsVariant::Protein(ProteinVariant {
                        accession: accession.clone(),
                        gene_symbol: gene_symbol.clone(),
                        loc_edit: LocEdit::with_uncertainty(interval, Mu::Uncertain(edit)),
                    }),
                ));
            }
        }

        // Try numeric-only protein repeat (e.g., p.223PA[3], p.179_180AP[9])
        // These have just a number position (no amino acid) followed by single-letter AA repeat
        if let Ok((remaining, variant)) =
            parse_protein_numeric_repeat(input, accession.clone(), gene_symbol.clone())
        {
            return Ok((remaining, variant));
        }

        // Try numeric-only protein position (e.g., p.78, p.4894Q)
        // These are non-standard but appear in ClinVar
        if let Ok((remaining, variant)) =
            parse_protein_numeric_position(input, accession.clone(), gene_symbol.clone())
        {
            return Ok((remaining, variant));
        }

        // Normal case: position + edit
        let (input, interval) = parse_prot_interval(input)?;

        // Try to parse an edit; if no edit is present and input is exhausted,
        // treat as position-specific unknown (common in VEP output like p.Met1_?4)
        let (input, edit) = match parse_protein_edit(input) {
            Ok((remaining, edit)) => (remaining, edit),
            Err(_) if input.is_empty() || input.starts_with(' ') || input.starts_with(',') => {
                // No edit specified - treat as position-specific unknown
                (input, ProteinEdit::position_unknown())
            }
            Err(e) => return Err(e),
        };

        Ok((
            input,
            HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse RNA variant (r.)
fn parse_rna_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("r.").parse(input)?;

        // Check for cis allele shorthand: r.[118_261del;118_373del]
        if input.starts_with('[') {
            return parse_rna_allele_shorthand(input, accession.clone(), gene_symbol.clone());
        }

        // Check for position-based unknown phase shorthand: r.100A>U(;)200del
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_rna_position_unknown_phase(input, accession.clone(), gene_symbol.clone());
        }

        // First try whole-RNA identity (r.=) - no position
        if let Ok((remaining, edit)) = parse_whole_rna_identity(input) {
            let dummy_pos = crate::hgvs::location::RnaPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = RnaInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try whole-RNA unknown (r.?) - no position
        if let Ok((remaining, edit)) = parse_whole_rna_unknown(input) {
            let dummy_pos = crate::hgvs::location::RnaPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = RnaInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try RNA-specific splice pattern (r.spl)
        if let Ok((remaining, edit)) = parse_rna_splice(input) {
            let dummy_pos = crate::hgvs::location::RnaPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = RnaInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try RNA-specific no product pattern (r.0)
        if let Ok((remaining, edit)) = parse_rna_no_product(input) {
            let dummy_pos = crate::hgvs::location::RnaPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = RnaInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(dummy_interval, edit),
                }),
            ));
        }

        // Try whole-RNA predicted splice (r.(spl) / r.(spl?)) — must come before the
        // generic predicted-variant parser, which requires an interval. The whole-entity
        // splicing marker has no positional content, so we attach a dummy interval and
        // wrap the edit in `Mu::Uncertain` so that `RnaVariant::fmt_loc_edit` emits the
        // surrounding parens.
        if let Ok((remaining, edit)) = parse_whole_rna_predicted_splice(input) {
            let dummy_pos = crate::hgvs::location::RnaPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = RnaInterval::point(dummy_pos);
            return Ok((
                remaining,
                HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit {
                        location: dummy_interval,
                        edit: Mu::Uncertain(edit),
                    },
                }),
            ));
        }

        // Try predicted RNA variant format: r.(interval edit)
        if let Ok((remaining, variant)) =
            parse_predicted_rna_variant(input, accession.clone(), gene_symbol.clone())
        {
            return Ok((remaining, variant));
        }

        let (input, interval) = parse_rna_interval(input)?;
        let (input, edit) = parse_na_edit(input)?;

        Ok((
            input,
            HgvsVariant::Rna(RnaVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse whole-RNA identity: r.=
fn parse_whole_rna_identity(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    map(tag("="), |_| {
        crate::hgvs::edit::NaEdit::whole_entity_identity()
    })
    .parse(input)
}

/// Parse whole-RNA unknown: r.?
fn parse_whole_rna_unknown(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    // Only match terminal ? (not ? followed by _ which indicates uncertain position)
    let (remaining, _) = tag("?").parse(input)?;
    if remaining.starts_with('_') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }
    Ok((remaining, crate::hgvs::edit::NaEdit::whole_entity_unknown()))
}

/// Parse RNA splice pattern: `spl` (very-likely-affected) or `spl?` (might-be-affected).
///
/// Per HGVS v21.0 (`assets/hgvs-nomenclature/docs/recommendations/RNA/splicing.md` and
/// `docs/recommendations/uncertain.md`):
/// - `r.spl`  — RNA not analysed; splicing very likely affected.
/// - `r.spl?` — RNA not analysed; splicing might be affected.
fn parse_rna_splice(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    let (input, _) = tag("spl").parse(input)?;
    let (input, marker) =
        nom::combinator::opt(tag::<_, _, nom::error::Error<&str>>("?")).parse(input)?;
    Ok((
        input,
        crate::hgvs::edit::NaEdit::Splice {
            unknown: marker.is_some(),
        },
    ))
}

/// Parse whole-RNA predicted splice pattern: `(spl)` or `(spl?)`.
///
/// Per HGVS v21.0, `r.(spl?)` is the canonical predicted-uncertain splicing marker;
/// `r.(spl)` is the symmetric predicted-but-certain form. Both are whole-entity edits
/// (no positional content), so we wrap the result in `Mu::Uncertain` rather than
/// dispatching through the generic `parse_predicted_rna_variant`, which requires an
/// interval. See `RnaVariant::fmt_loc_edit` for the matching Display path.
fn parse_whole_rna_predicted_splice(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    let (input, _) = tag("(").parse(input)?;
    let (input, edit) = parse_rna_splice(input)?;
    let (input, _) = tag(")").parse(input)?;
    Ok((input, edit))
}

/// Parse RNA no product pattern: r.0
fn parse_rna_no_product(input: &str) -> IResult<&str, crate::hgvs::edit::NaEdit> {
    // Match "0" but only as a standalone symbol (not followed by digits or other edit characters)
    let (remaining, _) = tag("0").parse(input)?;
    // Make sure it's not followed by more digits (would be a position)
    if remaining.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }
    Ok((remaining, crate::hgvs::edit::NaEdit::NoProduct))
}

/// Parse predicted RNA variant: r.(100_101insAUG)
fn parse_predicted_rna_variant(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Match opening paren
    let (input, _) = tag("(").parse(input)?;

    // Parse interval and edit inside parens
    let (input, interval) = parse_rna_interval(input)?;
    let (input, edit) = parse_na_edit(input)?;

    // Match closing paren
    let (input, _) = tag(")").parse(input)?;

    Ok((
        input,
        HgvsVariant::Rna(RnaVariant {
            accession,
            gene_symbol,
            loc_edit: LocEdit::new(interval, edit),
        }),
    ))
}

/// Parse position-based unknown phase shorthand for RNA: 100A>U(;)200del
fn parse_rna_position_unknown_phase(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(4);

    for part in input.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::Verify,
            )));
        }

        let (edit_remaining, interval) = parse_rna_interval(part)?;
        let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

        if !final_remaining.trim().is_empty() {
            return Err(nom::Err::Error(nom::error::Error::new(
                final_remaining,
                nom::error::ErrorKind::Tag,
            )));
        }

        variants.push(HgvsVariant::Rna(RnaVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.clone(),
            loc_edit: LocEdit::new(interval, edit),
        }));
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        "",
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Unknown)),
    ))
}

/// Parse RNA allele shorthand: [118_261del;118_373del], [100A>U(;)200del], or [100del];[0]
fn parse_rna_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    // Must start with [
    if !input.starts_with('[') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Check for trans allele pattern: [var];[var] or [var];[0] or [var];[?]
    if input.contains("];[") {
        return parse_rna_trans_allele_shorthand(input, accession, gene_symbol);
    }

    let close_bracket = input.rfind(']').ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;

    let content = &input[1..close_bracket];
    let remaining = &input[close_bracket + 1..];

    // Check for mixed phase: contains both ; and (;)
    let has_unknown_phase = content.contains("(;)");
    let has_cis_separator = {
        let temp = content.replace("(;)", "\x00");
        temp.contains(';')
    };

    let phase = if has_unknown_phase {
        AllelePhase::Unknown
    } else {
        AllelePhase::Cis
    };

    let mut variants = Vec::with_capacity(4);

    if has_unknown_phase && has_cis_separator {
        for unknown_group in content.split("(;)") {
            for part in unknown_group.split(';') {
                let part = part.trim();
                if part.is_empty() {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        input,
                        nom::error::ErrorKind::Verify,
                    )));
                }

                let (edit_remaining, interval) = parse_rna_interval(part)?;
                let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

                if !final_remaining.trim().is_empty() {
                    return Err(nom::Err::Error(nom::error::Error::new(
                        final_remaining,
                        nom::error::ErrorKind::Tag,
                    )));
                }

                variants.push(HgvsVariant::Rna(RnaVariant {
                    accession: accession.clone(),
                    gene_symbol: gene_symbol.clone(),
                    loc_edit: LocEdit::new(interval, edit),
                }));
            }
        }
    } else {
        let separator = if has_unknown_phase { "(;)" } else { ";" };

        for part in content.split(separator) {
            let part = part.trim();
            if part.is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    input,
                    nom::error::ErrorKind::Verify,
                )));
            }

            let (edit_remaining, interval) = parse_rna_interval(part)?;
            let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            variants.push(HgvsVariant::Rna(RnaVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }));
        }
    }

    if variants.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, phase)),
    ))
}

/// Parse RNA trans allele shorthand: [100del];[0], [100del];[?], [var1];[var2]
fn parse_rna_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = &remaining[1..close_bracket].trim();

        let variant = if *content == "0" {
            HgvsVariant::NullAllele
        } else if *content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_rna_interval(content)?;
            let (final_remaining, edit) = parse_na_edit(edit_remaining)?;

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Rna(RnaVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse circular DNA variant (o.) - SVD-WG006
fn parse_circular_variant(
    accession: Accession,
    gene_symbol: Option<String>,
) -> impl FnMut(&str) -> IResult<&str, HgvsVariant> {
    move |input: &str| {
        let (input, _) = tag("o.").parse(input)?;

        // Compact-prefix trans-allele shorthand: o.[a];[b]. Mirrors
        // parse_genome_variant's dispatch added in PR #146; SVD-WG006 says
        // circular DNA inherits the DNA allele grammar.
        if input.starts_with('[') && input.contains("];[") {
            if let Ok((remaining, variant)) =
                parse_circular_trans_allele_shorthand(input, accession.clone(), gene_symbol.clone())
            {
                return Ok((remaining, variant));
            }
        }

        // Bracketed compound allele: o.[var;var] or o.[var(;)var]
        if input.starts_with('[') {
            if let Ok((remaining, allele)) = parse_genome_kind_compound_allele(
                input,
                accession.clone(),
                gene_symbol.clone(),
                GenomeKind::Circular,
            ) {
                return Ok((remaining, HgvsVariant::Allele(allele)));
            }
        }

        // Bracketless unknown-phase shorthand: o.100A>G(;)200T>C (#123)
        if input.contains("(;)") && !input.starts_with('[') {
            return parse_genome_position_unknown_phase(
                input,
                accession.clone(),
                gene_symbol.clone(),
                GenomeKind::Circular,
            );
        }

        let (input, interval) = parse_genome_interval(input)?;
        let (input, edit) = parse_na_edit(input)?;

        Ok((
            input,
            HgvsVariant::Circular(CircularVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            }),
        ))
    }
}

/// Parse a circular DNA trans-allele compact-prefix shorthand:
/// `[edit1];[edit2]` (with the `o.` already consumed). Mirrors
/// `parse_genome_trans_allele_shorthand`; circular variants reuse
/// `parse_genome_interval`.
fn parse_circular_trans_allele_shorthand(
    input: &str,
    accession: Accession,
    gene_symbol: Option<String>,
) -> IResult<&str, HgvsVariant> {
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        if !remaining.starts_with('[') {
            break;
        }

        let close_bracket = remaining.find(']').ok_or_else(|| {
            nom::Err::Error(nom::error::Error::new(
                remaining,
                nom::error::ErrorKind::Tag,
            ))
        })?;

        let content = remaining[1..close_bracket].trim();

        let variant = if content == "0" {
            HgvsVariant::NullAllele
        } else if content == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (edit_remaining, interval) = parse_genome_interval(content)?;
            let (final_remaining, edit) = if let Ok((r, e)) = parse_na_edit(edit_remaining) {
                (r, e)
            } else {
                (
                    edit_remaining,
                    crate::hgvs::edit::NaEdit::Identity {
                        sequence: None,
                        whole_entity: false,
                    },
                )
            };

            if !final_remaining.trim().is_empty() {
                return Err(nom::Err::Error(nom::error::Error::new(
                    final_remaining,
                    nom::error::ErrorKind::Tag,
                )));
            }

            HgvsVariant::Circular(CircularVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.clone(),
                loc_edit: LocEdit::new(interval, edit),
            })
        };

        variants.push(variant);
        remaining = &remaining[close_bracket + 1..];

        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        }
    }

    if variants.len() < 2 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, AllelePhase::Trans)),
    ))
}

/// Parse a single variant (not an allele) from input
/// Returns the remaining input and the parsed variant
fn parse_single_variant(input: &str) -> Result<(&str, HgvsVariant), FerroError> {
    let trimmed = input.trim_start();

    // Parse accession
    let (remaining, accession) = parse_accession(trimmed).map_err(|e| FerroError::Parse {
        pos: 0,
        msg: format!("Failed to parse accession: {:?}", e),
        diagnostic: None,
    })?;

    // Parse gene symbol if present
    let (remaining, gene_symbol) = parse_gene_symbol(remaining).map_err(|e| FerroError::Parse {
        pos: trimmed.len() - remaining.len(),
        msg: format!("Failed to parse gene symbol: {:?}", e),
        diagnostic: None,
    })?;

    // Expect colon separator
    let remaining = remaining
        .strip_prefix(':')
        .ok_or_else(|| FerroError::Parse {
            pos: trimmed.len() - remaining.len(),
            msg: "Expected ':' after accession".to_string(),
            diagnostic: None,
        })?;

    // Dispatch based on type prefix
    let result = if remaining.starts_with('[') {
        // ClinVar-style allele: NM_xxx:[c.var1;c.var2] or NC_xxx:[g.var1;g.var2]
        return parse_clinvar_style_allele(remaining, &accession);
    } else if remaining.starts_with("c.") {
        parse_cds_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("p.") {
        parse_protein_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("g.") {
        parse_genome_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("n.") {
        parse_tx_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("r.") {
        parse_rna_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("m.") {
        parse_mt_variant(accession, gene_symbol).parse(remaining)
    } else if remaining.starts_with("o.") {
        parse_circular_variant(accession, gene_symbol).parse(remaining)
    } else {
        // Try to infer type from accession prefix and parse without type prefix
        let acc_prefix: &str = &accession.prefix;
        // For GenBank-style accessions like "AL513220", the entire name is the prefix,
        // so we also check if it starts with a known genomic prefix
        let is_genomic_prefix = acc_prefix == "NC"
            || acc_prefix == "NT"
            || acc_prefix == "NW"
            || acc_prefix == "AC"
            || acc_prefix == "NG"
            || acc_prefix.starts_with("AL")
            || acc_prefix.starts_with("BX")
            || acc_prefix.starts_with("CR")
            || acc_prefix.starts_with("CT")
            || acc_prefix.starts_with("CU");
        if is_genomic_prefix {
            // Genomic accession - try parsing as g. without the prefix
            let prefixed = format!("g.{}", remaining);
            match parse_genome_variant(accession.clone(), gene_symbol.clone()).parse(&prefixed) {
                Ok((rem, variant)) => {
                    // Adjust remaining - we consumed the same amount as the original remaining
                    let consumed = prefixed.len() - rem.len() - 2; // -2 for "g."
                    Ok((&remaining[consumed..], variant))
                }
                Err(_) => {
                    return Err(FerroError::Parse {
                        pos: trimmed.len() - remaining.len(),
                        msg: format!(
                            "Unknown variant type prefix: expected one of 'c.', 'g.', 'p.', 'n.', 'r.', 'm.', 'o.' but found '{}'",
                            remaining.chars().take(3).collect::<String>()
                        ),
                        diagnostic: None,
                    });
                }
            }
        } else if acc_prefix == "NM"
            || acc_prefix == "NR"
            || acc_prefix == "XM"
            || acc_prefix == "XR"
        {
            // Transcript accession - try parsing as c. without the prefix
            let prefixed = format!("c.{}", remaining);
            match parse_cds_variant(accession.clone(), gene_symbol.clone()).parse(&prefixed) {
                Ok((rem, variant)) => {
                    let consumed = prefixed.len() - rem.len() - 2; // -2 for "c."
                    Ok((&remaining[consumed..], variant))
                }
                Err(_) => {
                    return Err(FerroError::Parse {
                        pos: trimmed.len() - remaining.len(),
                        msg: format!(
                            "Unknown variant type prefix: expected one of 'c.', 'g.', 'p.', 'n.', 'r.', 'm.', 'o.' but found '{}'",
                            remaining.chars().take(3).collect::<String>()
                        ),
                        diagnostic: None,
                    });
                }
            }
        } else {
            return Err(FerroError::Parse {
                pos: trimmed.len() - remaining.len(),
                msg: format!(
                    "Unknown variant type prefix: expected one of 'c.', 'g.', 'p.', 'n.', 'r.', 'm.', 'o.' but found '{}'",
                    remaining.chars().take(3).collect::<String>()
                ),
                diagnostic: None,
            });
        }
    };

    match result {
        Ok((remaining, variant)) => Ok((remaining, variant)),
        Err(e) => Err(FerroError::Parse {
            pos: trimmed.len() - remaining.len(),
            msg: format!("Failed to parse variant: {:?}", e),
            diagnostic: None,
        }),
    }
}

/// Parse a ClinVar-style allele: NM_xxx:[c.var1;c.var2] or NC_xxx:[g.var1;g.var2]
/// This differs from the standard shorthand format NM_xxx:c.[var1;var2] by having
/// the variant type prefix (c., g., etc.) inside the brackets for each variant.
fn parse_clinvar_style_allele<'a>(
    input: &'a str,
    accession: &Accession,
) -> Result<(&'a str, HgvsVariant), FerroError> {
    // Must start with [
    if !input.starts_with('[') {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "ClinVar-style allele must start with '['".to_string(),
            diagnostic: None,
        });
    }

    // Find the matching closing bracket
    let close_bracket = input.rfind(']').ok_or_else(|| FerroError::Parse {
        pos: 0,
        msg: "ClinVar-style allele must end with ']'".to_string(),
        diagnostic: None,
    })?;

    let content = &input[1..close_bracket];
    let remaining = &input[close_bracket + 1..];

    // Check for unknown phase marker (;)
    let has_unknown_phase = content.contains("(;)");

    // Split by either (;) or ; to get individual variant parts
    let parts: Vec<&str> = if has_unknown_phase {
        // Split on (;) first, then on ;
        content
            .split("(;)")
            .flat_map(|part| part.split(';'))
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect()
    } else {
        content
            .split(';')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .collect()
    };

    if parts.is_empty() {
        return Err(FerroError::Parse {
            pos: 1,
            msg: "ClinVar-style allele must contain at least one variant".to_string(),
            diagnostic: None,
        });
    }

    // Parse each variant with the shared accession prepended
    let mut variants = Vec::new();
    for part in parts {
        // Prepend shared accession to each variant part (e.g., "c.100A>G" -> "NM_xxx.1:c.100A>G")
        let full_variant = format!("{}:{}", accession, part);
        let (_, variant) = parse_single_variant(&full_variant)?;
        variants.push(variant);
    }

    let phase = if has_unknown_phase {
        AllelePhase::Unknown
    } else {
        AllelePhase::Cis
    };

    Ok((
        remaining,
        HgvsVariant::Allele(AlleleVariant::new(variants, phase)),
    ))
}

/// Parse a cis allele: [var1;var2;...]
fn parse_cis_allele(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Must start with [
    if !input.starts_with('[') {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Cis allele must start with '['".to_string(),
            diagnostic: None,
        });
    }

    // Find the matching ]
    let close_bracket = input.rfind(']').ok_or_else(|| FerroError::Parse {
        pos: input.len(),
        msg: "Missing closing ']' in cis allele".to_string(),
        diagnostic: None,
    })?;

    // Check nothing after the closing bracket
    let after_bracket = &input[close_bracket + 1..];
    if !after_bracket.trim().is_empty() {
        return Err(FerroError::Parse {
            pos: close_bracket + 1,
            msg: format!("Unexpected trailing characters: '{}'", after_bracket),
            diagnostic: None,
        });
    }

    // Extract content inside brackets
    let content = &input[1..close_bracket];

    // Split by semicolon and parse each variant
    let mut variants = Vec::with_capacity(4);
    for part in content.split(';') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let (remaining, variant) = parse_single_variant(part)?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: 0,
                msg: format!("Unexpected content after variant: '{}'", remaining),
                diagnostic: None,
            });
        }
        variants.push(variant);
    }

    if variants.is_empty() {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Empty allele".to_string(),
            diagnostic: None,
        });
    }

    Ok(HgvsVariant::Allele(AlleleVariant::new(
        variants,
        AllelePhase::Cis,
    )))
}

/// Parse a trans allele: [var1];[var2];...
/// Also supports special markers: [0] (null allele) and [?] (unknown allele)
fn parse_trans_allele(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Must start with [
    if !input.starts_with('[') {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Trans allele must start with '['".to_string(),
            diagnostic: None,
        });
    }

    // Split by ];[ pattern
    let mut variants = Vec::with_capacity(2);
    let mut remaining = input;

    while !remaining.is_empty() {
        // Must start with [
        if !remaining.starts_with('[') {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: "Expected '[' in trans allele".to_string(),
                diagnostic: None,
            });
        }

        // Find closing bracket
        let close_bracket = remaining.find(']').ok_or_else(|| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: "Missing closing ']' in trans allele".to_string(),
            diagnostic: None,
        })?;

        // Parse the variant inside the brackets
        let variant_str = &remaining[1..close_bracket].trim();

        // Check for special markers
        let variant = if *variant_str == "0" {
            HgvsVariant::NullAllele
        } else if *variant_str == "?" {
            HgvsVariant::UnknownAllele
        } else {
            let (var_remaining, var) = parse_single_variant(variant_str)?;
            if !var_remaining.trim().is_empty() {
                return Err(FerroError::Parse {
                    pos: 0,
                    msg: format!("Unexpected content after variant: '{}'", var_remaining),
                    diagnostic: None,
                });
            }
            var
        };
        variants.push(variant);

        // Move past the closing bracket
        remaining = &remaining[close_bracket + 1..];

        // Check for more variants (semicolon separator)
        if remaining.starts_with(';') {
            remaining = &remaining[1..];
        } else if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Expected ';' or end of input, found: '{}'", remaining),
                diagnostic: None,
            });
        }
    }

    if variants.len() < 2 {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Trans allele requires at least two variants".to_string(),
            diagnostic: None,
        });
    }

    Ok(HgvsVariant::Allele(AlleleVariant::new(
        variants,
        AllelePhase::Trans,
    )))
}

/// Create an identity variant based on the type of the reference variant.
/// Used for mosaic/chimeric notation where "=" means reference allele.
fn create_identity_variant_from(reference: &HgvsVariant) -> Result<HgvsVariant, FerroError> {
    use crate::hgvs::edit::NaEdit;
    use crate::hgvs::location::{GenomePos, RnaPos, TxPos};

    match reference {
        HgvsVariant::Cds(cds) => {
            // Create c.= (whole-CDS identity)
            let dummy_pos = CdsPos {
                base: 1,
                offset: None,
                utr3: false,
            };
            let dummy_interval = CdsInterval::point(dummy_pos);
            Ok(HgvsVariant::Cds(CdsVariant {
                accession: cds.accession.clone(),
                gene_symbol: cds.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Genome(genome) => {
            // Create g.= (whole-genome identity)
            let dummy_interval = GenomeInterval::point(GenomePos::new(1));
            Ok(HgvsVariant::Genome(GenomeVariant {
                accession: genome.accession.clone(),
                gene_symbol: genome.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Tx(tx) => {
            // Create n.= (whole-transcript identity)
            let dummy_interval = TxInterval::point(TxPos::new(1));
            Ok(HgvsVariant::Tx(TxVariant {
                accession: tx.accession.clone(),
                gene_symbol: tx.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Rna(rna) => {
            // Create r.= (whole-RNA identity)
            let dummy_interval = RnaInterval::point(RnaPos::new(1));
            Ok(HgvsVariant::Rna(RnaVariant {
                accession: rna.accession.clone(),
                gene_symbol: rna.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Mt(mt) => {
            // Create m.= (whole-mitochondrial identity)
            let dummy_interval = GenomeInterval::point(GenomePos::new(1));
            Ok(HgvsVariant::Mt(MtVariant {
                accession: mt.accession.clone(),
                gene_symbol: mt.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Circular(circular) => {
            // Create o.= (whole-circular identity)
            let dummy_interval = GenomeInterval::point(GenomePos::new(1));
            Ok(HgvsVariant::Circular(CircularVariant {
                accession: circular.accession.clone(),
                gene_symbol: circular.gene_symbol.clone(),
                loc_edit: LocEdit::new(dummy_interval, NaEdit::whole_entity_identity()),
            }))
        }
        HgvsVariant::Protein(protein) => {
            // Create p.= (whole-protein identity)
            let dummy_interval = ProtInterval::point(ProtPos::new(AminoAcid::Met, 1));
            Ok(HgvsVariant::Protein(ProteinVariant {
                accession: protein.accession.clone(),
                gene_symbol: protein.gene_symbol.clone(),
                loc_edit: LocEdit::new(
                    dummy_interval,
                    crate::hgvs::edit::ProteinEdit::whole_protein_identity(),
                ),
            }))
        }
        _ => Err(FerroError::Parse {
            pos: 0,
            msg: "Cannot create identity variant for this variant type".to_string(),
            diagnostic: None,
        }),
    }
}

/// Parse a mosaic: var1/var2 (single slash)
/// Supports "=" as shorthand for reference allele (no change)
/// Supports accession inheritance: NM_000088.3:c.100A>G/c.200C>T
fn parse_mosaic_allele(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Split by single slash (but not double slash)
    let mut variants = Vec::with_capacity(2);
    let mut start = 0;
    let mut first_variant: Option<HgvsVariant> = None;
    let mut first_accession: Option<Accession> = None;
    let mut first_gene_symbol: Option<String> = None;

    while start < input.len() {
        // Find next single slash (not double)
        let mut found_slash = None;
        let bytes = input.as_bytes();
        for i in start..input.len() {
            if bytes[i] == b'/' {
                // Check if double slash
                if i + 1 < input.len() && bytes[i + 1] == b'/' {
                    // This is a chimeric separator, not mosaic
                    return Err(FerroError::Parse {
                        pos: i,
                        msg: "Found '//' (chimeric) but expected '/' (mosaic)".to_string(),
                        diagnostic: None,
                    });
                }
                found_slash = Some(i);
                break;
            }
        }

        let end = found_slash.unwrap_or(input.len());
        let variant_str = &input[start..end].trim();

        // Check for "=" shorthand meaning reference allele
        let variant = if *variant_str == "=" {
            // Need a reference variant to determine the type
            match &first_variant {
                Some(ref_var) => create_identity_variant_from(ref_var)?,
                None => {
                    return Err(FerroError::Parse {
                        pos: start,
                        msg: "Cannot use '=' as first variant in mosaic notation".to_string(),
                        diagnostic: None,
                    });
                }
            }
        } else {
            // Try parsing as a full variant first
            match parse_single_variant(variant_str) {
                Ok((remaining, var)) => {
                    if !remaining.trim().is_empty() {
                        return Err(FerroError::Parse {
                            pos: 0,
                            msg: format!("Unexpected content after variant: '{}'", remaining),
                            diagnostic: None,
                        });
                    }
                    var
                }
                Err(_) if first_accession.is_some() => {
                    // First fallback: parse with inherited accession + type prefix
                    // (long form `<acc>:m.<pos>=/m.<pos><ref>><alt>`).
                    match parse_variant_with_inherited_accession(
                        variant_str,
                        first_accession.as_ref().unwrap(),
                        first_gene_symbol.as_ref(),
                    ) {
                        Ok(var) => var,
                        Err(prefix_err) => {
                            // Second fallback: HGVS spec compact mosaic form
                            // `<acc>:<type>.<pos>=/<edit>` — RHS is a bare
                            // NaEdit, all metadata inherited from LHS. Only
                            // applies when LHS is `<pos>=` identity.
                            let lhs = first_variant
                                .as_ref()
                                .expect("first_accession set implies first_variant set");
                            match parse_compact_mosaic_rhs(variant_str, lhs)? {
                                Some(var) => var,
                                None => return Err(prefix_err),
                            }
                        }
                    }
                }
                Err(e) => return Err(e),
            }
        };

        if first_variant.is_none() {
            first_variant = Some(variant.clone());
            // Extract accession and gene symbol from first variant
            match &variant {
                HgvsVariant::Cds(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Genome(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Tx(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Rna(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Protein(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Mt(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                HgvsVariant::Circular(v) => {
                    first_accession = Some(v.accession.clone());
                    first_gene_symbol = v.gene_symbol.clone();
                }
                _ => {}
            }
        }
        variants.push(variant);

        if found_slash.is_some() {
            start = end + 1;
        } else {
            break;
        }
    }

    if variants.len() < 2 {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Mosaic allele requires at least two variants".to_string(),
            diagnostic: None,
        });
    }

    Ok(HgvsVariant::Allele(AlleleVariant::new(
        variants,
        AllelePhase::Mosaic,
    )))
}

/// Parse the RHS of a HGVS spec compact mosaic / chimeric form.
///
/// The spec compact form is `<acc>:<type>.<pos>=/<edit>` (mosaic) or
/// `<acc>:<type>.<pos>=//<edit>` (chimeric). The RHS is a bare edit
/// with no accession, type prefix, or position; it inherits all three
/// from the LHS, which must be a position-bound `=` identity edit.
///
/// Returns `Ok(None)` when the LHS is not eligible (so the caller can
/// fall through to its existing error path); returns `Ok(Some(_))` on
/// successful compact-form parse; returns `Err` only on a definite
/// compact-form parse error (e.g. trailing characters).
///
/// Per `recommendations/DNA/{substitution,deletion,duplication}.md`,
/// the form applies to substitution, deletion, and duplication on
/// nucleic-acid coord systems (`g.`, `c.`, `n.`, `r.`, `m.`, `o.`).
fn parse_compact_mosaic_rhs(
    rhs: &str,
    lhs: &HgvsVariant,
) -> Result<Option<HgvsVariant>, FerroError> {
    use crate::hgvs::edit::NaEdit;
    use crate::hgvs::parser::edit::parse_na_edit;

    // Eligibility: LHS must carry a position-bound (not whole-entity)
    // identity edit on a NA coord system.
    let lhs_is_eligible = match lhs {
        HgvsVariant::Genome(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        HgvsVariant::Cds(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        HgvsVariant::Tx(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        HgvsVariant::Rna(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        HgvsVariant::Mt(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        HgvsVariant::Circular(v) => matches!(
            v.loc_edit.edit.inner(),
            Some(NaEdit::Identity {
                whole_entity: false,
                ..
            })
        ),
        _ => false,
    };
    if !lhs_is_eligible {
        return Ok(None);
    }

    // Parse the RHS as a bare NaEdit and require we consumed all of it.
    let (remaining, edit) = match parse_na_edit(rhs) {
        Ok((rem, e)) => (rem, e),
        Err(_) => return Ok(None),
    };
    if !remaining.trim().is_empty() {
        return Err(FerroError::Parse {
            pos: rhs.len() - remaining.len(),
            msg: format!(
                "compact-mosaic RHS has unexpected trailing content: '{}'",
                remaining
            ),
            diagnostic: None,
        });
    }

    // Build the RHS variant by cloning LHS's accession + gene_symbol +
    // interval, swapping in the new edit. The Mu wrapper on the LHS
    // edit is replaced (we always emit Certain for the new RHS edit).
    let rhs_variant = match lhs {
        HgvsVariant::Genome(v) => HgvsVariant::Genome(GenomeVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        HgvsVariant::Cds(v) => HgvsVariant::Cds(CdsVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        HgvsVariant::Tx(v) => HgvsVariant::Tx(TxVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        HgvsVariant::Rna(v) => HgvsVariant::Rna(RnaVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        HgvsVariant::Mt(v) => HgvsVariant::Mt(MtVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        HgvsVariant::Circular(v) => HgvsVariant::Circular(CircularVariant {
            accession: v.accession.clone(),
            gene_symbol: v.gene_symbol.clone(),
            loc_edit: LocEdit::new(v.loc_edit.location.clone(), edit),
        }),
        _ => unreachable!("eligibility check guards against non-NA arms"),
    };
    Ok(Some(rhs_variant))
}

/// Parse a variant that inherits its accession from a previous variant
/// Used for mosaic/chimeric notation like NM_000088.3:c.100A>G/c.200C>T
fn parse_variant_with_inherited_accession(
    input: &str,
    accession: &Accession,
    gene_symbol: Option<&String>,
) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Check for type prefix and parse accordingly
    if let Some(rest) = input.strip_prefix("c.") {
        let (remaining, interval) = parse_cds_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse CDS interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_na_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Cds(CdsVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else if let Some(rest) = input.strip_prefix("g.") {
        let (remaining, interval) = parse_genome_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse genome interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_na_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Genome(GenomeVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else if let Some(rest) = input.strip_prefix("p.") {
        // Try whole-protein identity (p.= or p.(=))
        if let Ok((remaining, edit)) = parse_whole_protein_identity(rest) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            if !remaining.trim().is_empty() {
                return Err(FerroError::Parse {
                    pos: input.len() - remaining.len(),
                    msg: format!("Unexpected content: '{}'", remaining),
                    diagnostic: None,
                });
            }
            return Ok(HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.cloned(),
                loc_edit: LocEdit::new(dummy_interval, edit),
            }));
        }
        // Try whole-protein unknown (p.?)
        if let Ok((remaining, edit)) = parse_whole_protein_unknown(rest) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            if !remaining.trim().is_empty() {
                return Err(FerroError::Parse {
                    pos: input.len() - remaining.len(),
                    msg: format!("Unexpected content: '{}'", remaining),
                    diagnostic: None,
                });
            }
            return Ok(HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.cloned(),
                loc_edit: LocEdit::new(dummy_interval, edit),
            }));
        }
        // Try no protein (p.0)
        if let Ok((remaining, edit)) = parse_whole_protein_no_protein(rest) {
            let dummy_pos = ProtPos::new(AminoAcid::Met, 1);
            let dummy_interval = ProtInterval::point(dummy_pos);
            if !remaining.trim().is_empty() {
                return Err(FerroError::Parse {
                    pos: input.len() - remaining.len(),
                    msg: format!("Unexpected content: '{}'", remaining),
                    diagnostic: None,
                });
            }
            return Ok(HgvsVariant::Protein(ProteinVariant {
                accession: accession.clone(),
                gene_symbol: gene_symbol.cloned(),
                loc_edit: LocEdit::new(dummy_interval, edit),
            }));
        }
        // Normal case: position + edit
        let (remaining, interval) = parse_prot_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse protein interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_protein_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse protein edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Protein(ProteinVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else if let Some(rest) = input.strip_prefix("n.") {
        let (remaining, interval) = parse_tx_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse transcript interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_na_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Tx(TxVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else if let Some(rest) = input.strip_prefix("r.") {
        let (remaining, interval) = parse_rna_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse RNA interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_na_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Rna(RnaVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else if let Some(rest) = input.strip_prefix("m.") {
        let (remaining, interval) = parse_genome_interval(rest).map_err(|e| FerroError::Parse {
            pos: 2,
            msg: format!("Failed to parse mitochondrial interval: {:?}", e),
            diagnostic: None,
        })?;
        let (remaining, edit) = parse_na_edit(remaining).map_err(|e| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Failed to parse edit: {:?}", e),
            diagnostic: None,
        })?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected content: '{}'", remaining),
                diagnostic: None,
            });
        }
        Ok(HgvsVariant::Mt(MtVariant {
            accession: accession.clone(),
            gene_symbol: gene_symbol.cloned(),
            loc_edit: LocEdit::new(interval, edit),
        }))
    } else {
        Err(FerroError::Parse {
            pos: 0,
            msg: format!(
                "Unknown variant type prefix: expected one of 'c.', 'g.', 'p.', 'n.', 'r.', 'm.' but found '{}'",
                input.chars().take(3).collect::<String>()
            ),
            diagnostic: None,
        })
    }
}

/// Parse a chimeric: var1//var2 (double slash)
/// Supports "=" as shorthand for reference allele (no change)
fn parse_chimeric_allele(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Split by double slash
    let parts: Vec<&str> = input.split("//").collect();

    if parts.len() < 2 {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Chimeric allele requires '//' separator".to_string(),
            diagnostic: None,
        });
    }

    let mut variants = Vec::with_capacity(parts.len());
    let mut first_variant: Option<HgvsVariant> = None;

    for part in parts {
        let part = part.trim();
        if part.is_empty() {
            return Err(FerroError::Parse {
                pos: 0,
                msg: "Empty variant in chimeric allele".to_string(),
                diagnostic: None,
            });
        }

        // Check for "=" shorthand meaning reference allele
        let variant = if part == "=" {
            match &first_variant {
                Some(ref_var) => create_identity_variant_from(ref_var)?,
                None => {
                    return Err(FerroError::Parse {
                        pos: 0,
                        msg: "Cannot use '=' as first variant in chimeric notation".to_string(),
                        diagnostic: None,
                    });
                }
            }
        } else {
            match parse_single_variant(part) {
                Ok((remaining, var)) => {
                    if !remaining.trim().is_empty() {
                        return Err(FerroError::Parse {
                            pos: 0,
                            msg: format!("Unexpected content after variant: '{}'", remaining),
                            diagnostic: None,
                        });
                    }
                    var
                }
                Err(single_err) => match &first_variant {
                    Some(lhs) => {
                        // First fallback: parse with inherited accession + type
                        // prefix (long form `<acc>:m.<pos>=//m.<pos><ref>><alt>`).
                        // Mirrors the mosaic path so chimeric and mosaic accept
                        // the same set of equivalent input shapes.
                        let inherited = lhs.accession().and_then(|acc| {
                            let gs = lhs.gene_symbol().map(|s| s.to_string());
                            parse_variant_with_inherited_accession(part, acc, gs.as_ref()).ok()
                        });
                        match inherited {
                            Some(var) => var,
                            None => {
                                // Second fallback: HGVS spec compact chimeric
                                // form `<acc>:<type>.<pos>=//<edit>` — RHS is a
                                // bare NaEdit, all metadata inherited from LHS.
                                // Only applies when LHS is `<pos>=` identity.
                                match parse_compact_mosaic_rhs(part, lhs)? {
                                    Some(var) => var,
                                    None => return Err(single_err),
                                }
                            }
                        }
                    }
                    None => return Err(single_err),
                },
            }
        };

        if first_variant.is_none() {
            first_variant = Some(variant.clone());
        }
        variants.push(variant);
    }

    Ok(HgvsVariant::Allele(AlleleVariant::new(
        variants,
        AllelePhase::Chimeric,
    )))
}

/// Parse an unknown phase allele: [var1(;)var2(;)...]
fn parse_unknown_phase_allele(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Must start with [ and end with ]
    if !input.starts_with('[') || !input.ends_with(']') {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Unknown phase allele must be wrapped in brackets".to_string(),
            diagnostic: None,
        });
    }

    // Extract content inside brackets
    let content = &input[1..input.len() - 1];

    // Split by (;) and parse each variant. Empty groups (e.g.
    // `[A:c.x(;)(;)B:c.y]`, leading/trailing `(;)`) are malformed; reject
    // rather than silently dropping them — matches the per-coord helpers
    // (`parse_genome_kind_compound_allele` etc.) introduced for #123.
    let mut variants = Vec::with_capacity(2);
    for part in content.split("(;)") {
        let part = part.trim();
        if part.is_empty() {
            return Err(FerroError::Parse {
                pos: 0,
                msg: "Empty `(;)` group in unknown-phase allele".to_string(),
                diagnostic: None,
            });
        }
        let (remaining, variant) = parse_single_variant(part)?;
        if !remaining.trim().is_empty() {
            return Err(FerroError::Parse {
                pos: 0,
                msg: format!("Unexpected content after variant: '{}'", remaining),
                diagnostic: None,
            });
        }
        variants.push(variant);
    }

    if variants.is_empty() {
        return Err(FerroError::Parse {
            pos: 0,
            msg: "Empty allele".to_string(),
            diagnostic: None,
        });
    }

    Ok(HgvsVariant::Allele(AlleleVariant::new(
        variants,
        AllelePhase::Unknown,
    )))
}

/// Determine the type of allele from the input string
fn detect_allele_type(input: &str) -> Option<&'static str> {
    let input = input.trim();

    // Check for trans: [var];[var] pattern
    if input.starts_with('[') && input.contains("];[") {
        return Some("trans");
    }

    // Check for unknown phase: [var(;)var] pattern
    if input.starts_with('[') && input.ends_with(']') && input.contains("(;)") {
        return Some("unknown_phase");
    }

    // Check for cis: [var;var] pattern (single bracket wrapping all)
    if input.starts_with('[') && input.ends_with(']') && !input.contains("];[") {
        // Verify it contains ; inside brackets
        let inner = &input[1..input.len() - 1];
        if inner.contains(';') {
            return Some("cis");
        }
    }

    // Check for chimeric: var//var (double slash - check before single slash)
    if input.contains("//") {
        return Some("chimeric");
    }

    // Check for mosaic: var/var (single slash)
    // But not if it looks like a regular variant (no slash in accession part)
    if input.contains('/') {
        // Make sure the slash is between variants, not inside one
        // A simple heuristic: if there's a colon before the slash, it might be a mosaic
        if let Some(slash_pos) = input.find('/') {
            let before_slash = &input[..slash_pos];
            if before_slash.contains(':') {
                return Some("mosaic");
            }
        }
    }

    // Check for RNA fusion: accession:r.interval::accession:r.interval
    // The pattern has ":r." followed by "::" somewhere in the string
    if input.contains(":r.") && input.contains("::") {
        // Find :: and ensure it's between two r. parts
        if let Some(fusion_pos) = input.find("::") {
            let before = &input[..fusion_pos];
            let after = &input[fusion_pos + 2..];
            // Both parts should contain r. or the second should start with accession:r.
            if before.contains(":r.") && (after.contains(":r.") || after.starts_with("r.")) {
                return Some("rna_fusion");
            }
        }
    }

    None
}

/// Parse an RNA fusion variant - SVD-WG007
///
/// Format: `accession:r.interval::accession:r.interval`
/// Example: `NM_152263.2:r.-115_775::NM_002609.3:r.1580_*1924`
fn parse_rna_fusion(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Find the :: separator
    let fusion_pos = input.find("::").ok_or_else(|| FerroError::Parse {
        pos: 0,
        msg: "RNA fusion requires '::' separator".to_string(),
        diagnostic: None,
    })?;

    let five_prime_str = &input[..fusion_pos];
    let three_prime_str = &input[fusion_pos + 2..];

    // Parse the 5' partner
    let five_prime = parse_rna_fusion_breakpoint(five_prime_str)?;

    // Parse the 3' partner
    let three_prime = parse_rna_fusion_breakpoint(three_prime_str)?;

    Ok(HgvsVariant::RnaFusion(RnaFusionVariant::new(
        five_prime,
        three_prime,
    )))
}

/// Parse a single RNA fusion breakpoint (accession:r.interval)
fn parse_rna_fusion_breakpoint(input: &str) -> Result<RnaFusionBreakpoint, FerroError> {
    let input = input.trim();

    // Parse accession
    let (remaining, accession) = parse_accession(input).map_err(|e| FerroError::Parse {
        pos: 0,
        msg: format!("Failed to parse fusion accession: {:?}", e),
        diagnostic: None,
    })?;

    // Parse gene symbol if present
    let (remaining, gene_symbol) = parse_gene_symbol(remaining).map_err(|e| FerroError::Parse {
        pos: input.len() - remaining.len(),
        msg: format!("Failed to parse gene symbol: {:?}", e),
        diagnostic: None,
    })?;

    // Expect :r.
    let remaining = remaining
        .strip_prefix(":r.")
        .ok_or_else(|| FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: "Expected ':r.' in RNA fusion breakpoint".to_string(),
            diagnostic: None,
        })?;

    // Parse the RNA interval
    let (remaining, interval) = parse_rna_interval(remaining).map_err(|e| FerroError::Parse {
        pos: input.len() - remaining.len(),
        msg: format!("Failed to parse RNA interval: {:?}", e),
        diagnostic: None,
    })?;

    if !remaining.is_empty() {
        return Err(FerroError::Parse {
            pos: input.len() - remaining.len(),
            msg: format!("Unexpected content after RNA interval: '{}'", remaining),
            diagnostic: None,
        });
    }

    Ok(RnaFusionBreakpoint {
        accession,
        gene_symbol,
        interval,
    })
}

/// Parse a complete HGVS variant string
///
/// The parser is optimized with:
/// - Early type prefix checking to avoid unnecessary work
/// - Variant types ordered by frequency (c. > p. > g. > n. > r. > m.)
/// - Allele detection for compound variants
pub fn parse_variant(input: &str) -> Result<HgvsVariant, FerroError> {
    let input = input.trim();

    // Check for allele patterns and RNA fusion first
    let variant = if let Some(allele_type) = detect_allele_type(input) {
        match allele_type {
            "cis" => parse_cis_allele(input)?,
            "trans" => parse_trans_allele(input)?,
            "mosaic" => parse_mosaic_allele(input)?,
            "chimeric" => parse_chimeric_allele(input)?,
            "unknown_phase" => parse_unknown_phase_allele(input)?,
            "rna_fusion" => parse_rna_fusion(input)?,
            _ => unreachable!(),
        }
    } else {
        // Parse as single variant
        let (remaining, v) = parse_single_variant(input)?;
        if !remaining.is_empty() {
            return Err(FerroError::Parse {
                pos: input.len() - remaining.len(),
                msg: format!("Unexpected trailing characters: '{}'", remaining),
                diagnostic: None,
            });
        }
        v
    };

    // Spec-mandated post-parse semantic check: reject self-cancelling alleles
    // (HGVS recommendations/general.md line 47, tracked under issue #115).
    validate_no_self_cancelling(&variant)?;

    Ok(variant)
}

/// Walk the variant tree and reject any `AlleleVariant` that contains an
/// overlapping `del` + `dup` pair (HGVS `recommendations/general.md` line 47:
/// "descriptions removing part of a reference sequence replacing it with
/// part of the same sequence are not allowed").
fn validate_no_self_cancelling(variant: &HgvsVariant) -> Result<(), FerroError> {
    use crate::error::{Diagnostic, ErrorCode};
    if let HgvsVariant::Allele(allele) = variant {
        // Only cis-phase alleles describe edits on the same physical sequence.
        // Trans/mosaic/chimeric place the edits on different alleles or cell
        // populations, so an overlapping del+dup is not self-cancelling.
        // Unknown phase is treated permissively to avoid false rejections.
        if matches!(allele.phase, AllelePhase::Cis) {
            if let Some((dl, du)) =
                crate::hgvs::variant::AlleleVariant::detect_self_cancelling_pair(&allele.variants)
            {
                return Err(FerroError::Parse {
                    pos: 0,
                    msg: format!(
                        "Self-cancelling allele: variants at index {} (del) and {} (dup) describe \
                         overlapping reference positions",
                        dl, du
                    ),
                    diagnostic: Some(Box::new(
                        Diagnostic::new()
                            .with_code(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 47); drop one edit or rewrite \
                                 as a single delins",
                            ),
                    )),
                });
            }
        }
        // Recurse for nested alleles.
        for inner in &allele.variants {
            validate_no_self_cancelling(inner)?;
        }
    }
    Ok(())
}

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

    #[test]
    fn test_parse_genomic_substitution() {
        let variant = parse_variant("NC_000001.11:g.12345A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            variant.accession().expect("Expected accession").full(),
            "NC_000001.11"
        );
        assert_eq!(format!("{}", variant), "NC_000001.11:g.12345A>G");
    }

    #[test]
    fn test_parse_genomic_deletion() {
        let variant = parse_variant("NC_000001.11:g.12345_12350del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.12345_12350del");
    }

    #[test]
    fn test_parse_cds_substitution() {
        let variant = parse_variant("NM_000088.3:c.459A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.459A>G");
    }

    #[test]
    fn test_parse_cds_deletion() {
        let variant = parse_variant("NM_000088.3:c.459del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_cds_intronic() {
        let variant = parse_variant("NM_000088.3:c.459+5G>A").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.459+5G>A");
    }

    #[test]
    fn test_parse_cds_intronic_uncertain_offset() {
        // Uncertain positive offset (+?)
        let variant = parse_variant("NM_000088.3:c.100+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100+?del");

        // Uncertain negative offset (-?)
        let variant = parse_variant("NM_000088.3:c.100-?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100-?del");

        // Range with uncertain offsets on both ends
        let variant = parse_variant("NM_000088.3:c.548-?_5193+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.548-?_5193+?del");

        // Complex uncertain position with range boundary
        let variant = parse_variant("NM_000088.3:c.(?_-1)_328+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.(?_-1)_328+?del");
    }

    #[test]
    fn test_parse_cds_inverted_intronic_range() {
        // Inverted intronic ranges where base positions appear "inverted" but are valid
        // These represent intronic regions spanning exon boundaries
        let variant = parse_variant("NM_000088.3:c.85-47_84+48del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.85-47_84+48del");

        let variant = parse_variant("NM_000088.3:c.86-46_85+47insA").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.86-46_85+47insA");

        // Delins with explicit deleted sequence is preserved on round-trip
        // (issue #120). Use canonicalize_edit / canonicalization to strip
        // the explicit deleted form when desired.
        let variant = parse_variant("NM_000088.3:c.85-47_84+48delGCCAinsG").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_000088.3:c.85-47_84+48delGCCAinsG"
        );
    }

    #[test]
    fn test_parse_cds_utr() {
        let variant = parse_variant("NM_000088.3:c.-20G>A").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.-20G>A");

        let variant = parse_variant("NM_000088.3:c.*50G>A").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.*50G>A");
    }

    #[test]
    fn test_parse_whole_cds_unknown() {
        // Whole-CDS unknown: c.?
        let variant = parse_variant("NM_000088.3:c.?").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.?");
    }

    #[test]
    fn test_parse_transcript_variant() {
        let variant = parse_variant("NR_000001.1:n.100A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Tx(_)));
    }

    #[test]
    fn test_parse_protein_substitution() {
        let variant = parse_variant("NP_000079.2:p.Val600Glu").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
    }

    #[test]
    fn test_parse_protein_frameshift() {
        let variant = parse_variant("NP_000079.2:p.Lys23fs").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));

        // Frameshift with new amino acid
        let variant = parse_variant("NP_000079.2:p.Arg97ProfsTer23").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Arg97ProfsTer23");
    }

    #[test]
    fn test_parse_insertion() {
        let variant = parse_variant("NM_000088.3:c.459_460insATG").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.459_460insATG");
    }

    #[test]
    fn test_parse_duplication() {
        let variant = parse_variant("NM_000088.3:c.459dup").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_invalid() {
        let result = parse_variant("invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_with_trailing() {
        let result = parse_variant("NC_000001.11:g.12345A>G extra");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_uncertain_genomic_deletion() {
        // Uncertain range deletion: (100_200)del
        let variant = parse_variant("NC_000001.11:g.(12345_12350)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.(12345)_(12350)del");
    }

    #[test]
    fn test_parse_uncertain_cds_deletion() {
        // Uncertain range deletion
        let variant = parse_variant("NM_000088.3:c.(100_200)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.(100)_(200)del");
    }

    #[test]
    fn test_parse_individual_uncertain_positions() {
        // Individual uncertain positions
        let variant = parse_variant("NC_000001.11:g.(100)_(200)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.(100)_(200)del");
    }

    #[test]
    fn test_parse_mixed_uncertainty() {
        // One certain, one uncertain
        let variant = parse_variant("NC_000001.11:g.100_(200)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.100_(200)del");
    }

    #[test]
    fn test_parse_rna_substitution() {
        let variant = parse_variant("NM_000088.3:r.100a>g").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        // RNA uses lowercase nucleotides per HGVS spec
        assert_eq!(format!("{}", variant), "NM_000088.3:r.100a>g");
    }

    #[test]
    fn test_parse_rna_deletion() {
        let variant = parse_variant("NM_000088.3:r.100_200del").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:r.100_200del");
    }

    #[test]
    fn test_parse_rna_insertion() {
        let variant = parse_variant("NM_000088.3:r.100_101insaug").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        // RNA uses lowercase nucleotides per HGVS spec
        assert_eq!(format!("{}", variant), "NM_000088.3:r.100_101insaug");
    }

    #[test]
    fn test_parse_rna_with_offset() {
        // Intronic RNA position
        let variant = parse_variant("NM_000088.3:r.100+5a>g").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        // RNA uses lowercase nucleotides per HGVS spec
        assert_eq!(format!("{}", variant), "NM_000088.3:r.100+5a>g");
    }

    #[test]
    fn test_parse_rna_uncertain() {
        let variant = parse_variant("NM_000088.3:r.(100_200)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:r.(100)_(200)del");
    }

    #[test]
    fn test_parse_rna_utr() {
        // 5' UTR position - RNA uses lowercase nucleotides per HGVS spec
        let variant = parse_variant("NM_000088.3:r.-14a>c").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:r.-14a>c");

        // 3' UTR position - RNA uses lowercase nucleotides per HGVS spec
        let variant = parse_variant("NM_000088.3:r.*41u>a").unwrap();
        assert!(matches!(variant, HgvsVariant::Rna(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:r.*41u>a");
    }

    #[test]
    fn test_parse_protein_identity() {
        // Whole protein identity (p.=)
        let variant = parse_variant("NP_000079.2:p.=").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.=");
    }

    #[test]
    fn test_parse_protein_identity_predicted() {
        // Predicted whole protein identity (p.(=))
        let variant = parse_variant("NP_000079.2:p.(=)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.(=)");
    }

    #[test]
    fn test_parse_protein_position_identity() {
        // Position-specific identity (p.Val600=)
        let variant = parse_variant("NP_000079.2:p.Val600=").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Val600=");
    }

    #[test]
    fn test_parse_protein_no_protein() {
        // No protein produced (p.0)
        let variant = parse_variant("NP_000079.2:p.0").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.0");
    }

    #[test]
    fn test_parse_protein_no_protein_predicted() {
        // Predicted no protein (p.0?)
        let variant = parse_variant("NP_000079.2:p.0?").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.0?");
    }

    #[test]
    fn test_parse_protein_start_codon_substitution() {
        // Start codon substitution (p.Met1Leu)
        let variant = parse_variant("NP_000079.2:p.Met1Leu").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Met1Leu");
    }

    #[test]
    fn test_parse_protein_start_codon_deletion() {
        // Start codon deletion (p.Met1del)
        let variant = parse_variant("NP_000079.2:p.Met1del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Met1del");
    }

    #[test]
    fn test_parse_protein_start_codon_extension() {
        // Start codon N-terminal extension (p.Met1ext-5)
        let variant = parse_variant("NP_000079.2:p.Met1ext-5").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Met1ext-5");
    }

    #[test]
    fn test_parse_protein_start_codon_uncertain() {
        // Uncertain effect on start codon (p.Met1?)
        let variant = parse_variant("NP_000079.2:p.Met1?").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Met1?");
    }

    #[test]
    fn test_parse_protein_unusual_range() {
        // Unusual protein range with unknown amino acid (p.Met1_?4)
        // This is VEP-style notation where ?4 means "unknown amino acid at position 4"
        let variant = parse_variant("XP_005261260.1:p.Met1_?4").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        // The output normalizes ?4 to Xaa4 and adds implicit ? edit
        assert_eq!(format!("{}", variant), "XP_005261260.1:p.Met1_Xaa4?");

        // Another unusual range
        let variant = parse_variant("NP_000079.2:p.Gly100_?105").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Gly100_Xaa105?");
    }

    #[test]
    fn test_parse_protein_uncertain_range_boundaries() {
        // Uncertain start boundary: (?_Met1)_Glu2del
        // Means somewhere from unknown to Met1, then definitely to Glu2
        let variant = parse_variant("NP_001005484.1:p.(?_Met1)_Glu2del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_001005484.1:p.(?_Met1)_Glu2del");

        // Uncertain start boundary with known endpoint: (Met1_?)_Glu2del
        // Means somewhere from Met1 to unknown, then definitely to Glu2
        let variant = parse_variant("NP_001005484.1:p.(Met1_?)_Glu2del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_001005484.1:p.(Met1_?)_Glu2del");

        // Uncertain end boundary: Met1_(Glu2_?)del
        // Means definitely Met1, then somewhere from Glu2 to unknown
        let variant = parse_variant("NP_001005484.1:p.Met1_(Glu2_?)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_001005484.1:p.Met1_(Glu2_?)del");

        // Both uncertain: (?_Met1)_(Glu2_?)del
        let variant = parse_variant("NP_001005484.1:p.(?_Met1)_(Glu2_?)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(
            format!("{}", variant),
            "NP_001005484.1:p.(?_Met1)_(Glu2_?)del"
        );
    }

    #[test]
    fn test_parse_protein_nested_uncertain_positions() {
        // Deeply nested uncertain positions: Met(?_1)_Glu2(?)
        // This is AminoAcid with position range followed by AminoAcid with uncertain position
        let variant = parse_variant("NP_000088.1:p.Met(?_1)_Glu2(?)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        // Format output may vary based on internal representation

        // AminoAcid with just (?) - fully uncertain position
        let variant = parse_variant("NP_000088.1:p.Ter(?)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));

        // Combined with range: His1811_Ter(?)
        let variant = parse_variant("NP_000088.1:p.His1811_Ter(?)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));

        // AminoAcid with position range (?_N)
        let variant = parse_variant("NP_000088.1:p.Met(?_5)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));

        // AminoAcid with position range (N_?)
        let variant = parse_variant("NP_000088.1:p.Glu(3_?)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
    }

    #[test]
    fn test_parse_conversion() {
        // Gene conversion
        let variant = parse_variant("NM_000088.3:c.100_200conNM_000089.1:c.50_150").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_000088.3:c.100_200conNM_000089.1:c.50_150"
        );
    }

    #[test]
    fn test_parse_genomic_conversion() {
        // Genomic conversion
        let variant = parse_variant("NC_000001.11:g.12345_12400conNC_000002.12:g.100_155").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000001.11:g.12345_12400conNC_000002.12:g.100_155"
        );
    }

    #[test]
    fn test_parse_position_based_conversion() {
        // Position-based conversion (same chromosome)
        let variant =
            parse_variant("NC_000017.11:g.42522624_42522669con42536337_42536382").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000017.11:g.42522624_42522669con42536337_42536382"
        );
    }

    #[test]
    fn test_parse_repeat_exact() {
        // Exact repeat count
        let variant = parse_variant("NM_000088.3:c.100CAG[12]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100CAG[12]");
    }

    #[test]
    fn test_parse_repeat_range() {
        // Range repeat count
        let variant = parse_variant("NM_000088.3:c.100CAG[10_15]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100CAG[10_15]");
    }

    #[test]
    fn test_parse_repeat_min_uncertain() {
        // Minimum with uncertain maximum
        let variant = parse_variant("NM_000088.3:c.100CAG[10_?]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100CAG[10_?]");
    }

    #[test]
    fn test_parse_repeat_max_uncertain() {
        // Maximum with uncertain minimum
        let variant = parse_variant("NM_000088.3:c.100CAG[?_20]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100CAG[?_20]");
    }

    #[test]
    fn test_parse_repeat_unknown() {
        // Fully unknown count
        let variant = parse_variant("NM_000088.3:c.100CAG[?]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100CAG[?]");
    }

    #[test]
    fn test_parse_unknown_end_position() {
        // Unknown end position: c.1_?del
        let variant = parse_variant("NM_000088.3:c.1_?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.1_?del");
    }

    #[test]
    fn test_parse_unknown_start_position() {
        // Unknown start position: c.?_100del
        let variant = parse_variant("NM_000088.3:c.?_100del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.?_100del");
    }

    #[test]
    fn test_parse_genomic_unknown_position() {
        // Genomic with unknown positions
        let variant = parse_variant("NC_000001.11:g.100_?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.100_?del");

        let variant = parse_variant("NC_000001.11:g.?_200del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000001.11:g.?_200del");
    }

    #[test]
    fn test_parse_transcript_unknown_position() {
        // Transcript with unknown positions
        let variant = parse_variant("NR_000001.1:n.100_?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Tx(_)));
        assert_eq!(format!("{}", variant), "NR_000001.1:n.100_?del");
    }

    #[test]
    fn test_parse_whole_cds_identity() {
        // Whole-CDS identity: c.=
        let variant = parse_variant("NM_000088.3:c.=").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.=");
    }

    #[test]
    fn test_parse_position_specific_identity() {
        // Position-specific identity: c.100=
        let variant = parse_variant("NM_000088.3:c.100=").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100=");
    }

    #[test]
    fn test_parse_whole_protein_unknown() {
        // Whole-protein unknown: p.?
        let variant = parse_variant("NP_000079.2:p.?").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.?");

        // Predicted whole-protein unknown: p.(?)
        let variant = parse_variant("NP_000079.2:p.(?)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.(?)");
    }

    #[test]
    fn test_parse_position_specific_unknown() {
        // Position-specific unknown: p.Met1?
        let variant = parse_variant("NP_000079.2:p.Met1?").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.Met1?");
    }

    #[test]
    fn test_parse_predicted_protein_substitution() {
        // Predicted protein substitution: p.(Arg248Gln)
        let variant = parse_variant("NP_000079.2:p.(Arg248Gln)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.(Arg248Gln)");
    }

    #[test]
    fn test_parse_predicted_protein_frameshift() {
        // Predicted protein frameshift: p.(Lys23fs)
        let variant = parse_variant("NP_000079.2:p.(Lys23fs)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.(Lys23fs)");
    }

    #[test]
    fn test_parse_predicted_protein_deletion() {
        // Predicted protein deletion: p.(Val600del)
        let variant = parse_variant("NP_000079.2:p.(Val600del)").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        assert_eq!(format!("{}", variant), "NP_000079.2:p.(Val600del)");
    }

    #[test]
    fn test_parse_complex_cds_interval_exon_deletion() {
        // Complex interval with intronic breakpoints: c.(4185+1_4186-1)_(4357+1_4358-1)del
        let variant = parse_variant("NM_007294.4:c.(4185+1_4186-1)_(4357+1_4358-1)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_007294.4:c.(4185+1_4186-1)_(4357+1_4358-1)del"
        );
    }

    #[test]
    fn test_parse_complex_cds_interval_with_unknown() {
        // Complex interval with unknown start: c.(?_-1)_(96+1_97-1)del
        let variant = parse_variant("NM_000546.6:c.(?_-1)_(96+1_97-1)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_000546.6:c.(?_-1)_(96+1_97-1)del"
        );
    }

    #[test]
    fn test_parse_complex_genome_interval_uncertain_boundaries() {
        // Complex genomic interval with unknown boundaries: g.(?_43044294)_(43125364_?)del
        let variant = parse_variant("NC_000017.11:g.(?_43044294)_(43125364_?)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000017.11:g.(?_43044294)_(43125364_?)del"
        );
    }

    #[test]
    fn test_parse_simple_uncertain_boundary() {
        // Simple uncertain boundary: c.(4_6)_246del
        // The start position is uncertain (somewhere between 4 and 6)
        let variant = parse_variant("NM_000001.1:c.(4_6)_246del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000001.1:c.(4_6)_246del");

        // Also test with uncertain end position
        let variant = parse_variant("NM_000001.1:c.100_(200_250)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000001.1:c.100_(200_250)del");

        // Both positions uncertain
        let variant = parse_variant("NM_000001.1:c.(4_6)_(200_250)del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_000001.1:c.(4_6)_(200_250)del");
    }

    // Allele parsing tests

    #[test]
    fn test_parse_cis_allele() {
        // Cis allele: [var1;var2]
        let variant = parse_variant("[NM_000088.3:c.100A>G;NM_000088.3:c.200C>T]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
        }
        // Same-accession cis alleles render in compact form
        assert_eq!(format!("{}", variant), "NM_000088.3:c.[100A>G;200C>T]");
    }

    #[test]
    fn test_parse_trans_allele() {
        // Trans allele: [var1];[var2]
        let variant = parse_variant("[NM_000088.3:c.100A>G];[NM_000088.3:c.200C>T]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Trans);
            assert_eq!(allele.variants.len(), 2);
        }
        // Same-accession trans alleles render in compact form
        assert_eq!(format!("{}", variant), "NM_000088.3:c.[100A>G];[200C>T]");
    }

    #[test]
    fn test_parse_mosaic_allele() {
        // Mosaic: var1/var2
        let variant = parse_variant("NM_000088.3:c.100A>G/NM_000088.3:c.200C>T").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Mosaic);
            assert_eq!(allele.variants.len(), 2);
        }
        assert_eq!(
            format!("{}", variant),
            "NM_000088.3:c.100A>G/NM_000088.3:c.200C>T"
        );
    }

    #[test]
    fn test_parse_mosaic_with_reference() {
        // Mosaic with reference allele shorthand: var/=
        let variant = parse_variant("NM_000088.3:c.123A>G/=").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Mosaic);
            assert_eq!(allele.variants.len(), 2);
            // First variant should be the mutation
            assert!(matches!(&allele.variants[0], HgvsVariant::Cds(_)));
            // Second variant should be identity (reference)
            if let HgvsVariant::Cds(cds) = &allele.variants[1] {
                assert!(cds
                    .loc_edit
                    .edit
                    .inner()
                    .map(|e| e.is_whole_entity_identity())
                    .unwrap_or(false));
            } else {
                panic!("Expected CDS variant");
            }
        }
        // Roundtrip in spec compact form (#133 work item 3): the RHS `=`
        // shorthand emits as bare `=`, not as a synthetic identity at
        // position 1.
        assert_eq!(format!("{}", variant), "NM_000088.3:c.123A>G/=");
    }

    #[test]
    fn test_parse_chimeric_with_reference() {
        // Chimeric with reference allele shorthand: var//=
        let variant = parse_variant("NM_000088.3:c.456C>T//=").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Chimeric);
            assert_eq!(allele.variants.len(), 2);
        }
        // Roundtrip in spec compact form (#133 work item 3).
        assert_eq!(format!("{}", variant), "NM_000088.3:c.456C>T//=");
    }

    #[test]
    fn test_parse_mosaic_reference_first_fails() {
        // Cannot use = as first variant
        let result = parse_variant("=/NM_000088.3:c.123A>G");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_chimeric_allele() {
        // Chimeric: var1//var2
        let variant = parse_variant("NM_000088.3:c.100A>G//NM_000088.3:c.200C>T").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Chimeric);
            assert_eq!(allele.variants.len(), 2);
        }
        assert_eq!(
            format!("{}", variant),
            "NM_000088.3:c.100A>G//NM_000088.3:c.200C>T"
        );
    }

    #[test]
    fn test_parse_unknown_phase_allele() {
        // Unknown phase allele: [var1(;)var2]
        let variant = parse_variant("[NM_000088.3:c.100A>G(;)NM_000088.3:c.200C>T]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 2);
        }
        // Same-accession unknown-phase alleles render in compact form
        assert_eq!(format!("{}", variant), "NM_000088.3:c.100A>G(;)200C>T");
    }

    #[test]
    fn test_parse_unknown_phase_allele_multiple() {
        // Unknown phase allele with 3 variants
        let variant =
            parse_variant("[NM_000088.3:c.100A>G(;)NM_000088.3:c.200C>T(;)NM_000088.3:c.300G>A]")
                .unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 3);
        }
    }

    #[test]
    fn test_parse_cis_allele_shorthand() {
        // Cis allele shorthand: NM_000088.3:c.[145C>T;147C>G]
        let variant = parse_variant("NM_000088.3:c.[145C>T;147C>G]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
            // Both variants should have the same accession
            for v in &allele.variants {
                assert_eq!(
                    v.accession().expect("Expected accession").full(),
                    "NM_000088.3"
                );
            }
        }
        // Output uses compact form (same accession)
        assert_eq!(format!("{}", variant), "NM_000088.3:c.[145C>T;147C>G]");
    }

    #[test]
    fn test_parse_unknown_phase_allele_shorthand() {
        // Unknown phase allele shorthand: NM_000088.3:c.[145C>T(;)147C>G]
        let variant = parse_variant("NM_000088.3:c.[145C>T(;)147C>G]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 2);
        }
        // Output uses compact form (same accession)
        assert_eq!(format!("{}", variant), "NM_000088.3:c.145C>T(;)147C>G");
    }

    #[test]
    fn test_parse_mixed_phase_allele_shorthand() {
        // Mixed phase allele: some cis (;) and some unknown ((;))
        // Pattern: [123A>G;456C>T(;)789G>A] means 123 and 456 are cis, unknown phase with 789
        let variant = parse_variant("NM_000088.3:c.[123A>G;456C>T(;)789G>A]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            // Overall phase is Unknown when there's any unknown phase
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 3);
        }
    }

    #[test]
    fn test_parse_mixed_phase_allele_shorthand_complex() {
        // More complex mixed phase: [A;B;C(;)D;E]
        let variant =
            parse_variant("NM_000088.3:c.[100A>G;200C>T;300G>A(;)400del;500dup]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 5);
        }
    }

    #[test]
    fn test_parse_allele_with_interval_only_variant() {
        // Allele where first variant is interval-only (no edit) - implies identity/reference
        // ClinVar pattern: g.[interval;interval_with_edit]
        let variant = parse_variant("NC_000023.10:g.[100_200;300_400dup]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
            // First variant should be identity
            if let HgvsVariant::Genome(v) = &allele.variants[0] {
                assert!(matches!(
                    v.loc_edit.edit,
                    crate::hgvs::uncertainty::Mu::Certain(
                        crate::hgvs::edit::NaEdit::Identity { .. }
                    )
                ));
            }
        }

        // Test with uncertain intervals (actual ClinVar pattern)
        let variant = parse_variant(
            "NC_000023.10:g.[(?_29619835)_(29843303_?);(?_30646799)_(30848980_?)dup]",
        )
        .unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.variants.len(), 2);
        }
    }

    #[test]
    fn test_parse_cis_allele_multiple_variants() {
        // Cis allele with 3 variants
        let variant =
            parse_variant("[NM_000088.3:c.100A>G;NM_000088.3:c.200C>T;NM_000088.3:c.300G>A]")
                .unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 3);
        }
    }

    #[test]
    fn test_parse_cis_allele_mixed_types() {
        // Cis allele with CDS and protein variants
        let variant = parse_variant("[NM_000088.3:c.100A>G;NP_000079.2:p.Val600Glu]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
            assert!(matches!(allele.variants[0], HgvsVariant::Cds(_)));
            assert!(matches!(allele.variants[1], HgvsVariant::Protein(_)));
        }
    }

    // ClinVar-style allele tests (variant type prefix inside brackets)

    #[test]
    fn test_parse_cis_allele_clinvar_format() {
        // ClinVar uses format: NM_xxx:[c.var1;c.var2] instead of NM_xxx:c.[var1;var2]
        let variant = parse_variant("NM_006876.2:[c.1168A>G;c.1217C>T]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
            // Both variants should be CDS variants with the shared accession
            assert!(
                matches!(&allele.variants[0], HgvsVariant::Cds(v) if v.accession.to_string() == "NM_006876.2")
            );
            assert!(
                matches!(&allele.variants[1], HgvsVariant::Cds(v) if v.accession.to_string() == "NM_006876.2")
            );
        }
    }

    #[test]
    fn test_parse_cis_allele_clinvar_format_genomic() {
        // ClinVar genomic format: NC_xxx:[g.var1;g.var2]
        let variant = parse_variant("NC_000017.11:[g.43094927del;g.43095845dup]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Cis);
            assert_eq!(allele.variants.len(), 2);
            assert!(matches!(&allele.variants[0], HgvsVariant::Genome(_)));
            assert!(matches!(&allele.variants[1], HgvsVariant::Genome(_)));
        }
    }

    #[test]
    fn test_parse_unknown_phase_allele_clinvar_format() {
        // ClinVar unknown phase format: NM_xxx:[c.var1(;)c.var2]
        let variant = parse_variant("NM_000088.3:[c.145C>T(;)c.147C>G]").unwrap();
        assert!(matches!(variant, HgvsVariant::Allele(_)));
        if let HgvsVariant::Allele(allele) = &variant {
            assert_eq!(allele.phase, AllelePhase::Unknown);
            assert_eq!(allele.variants.len(), 2);
        }
    }

    // === SVD-WG006: Circular DNA (o.) tests ===

    #[test]
    fn test_parse_circular_substitution() {
        // Using NC_ (chromosome) for circular plasmid (common pattern)
        let variant = parse_variant("NC_001416.1:o.100A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Circular(_)));
        assert_eq!(format!("{}", variant), "NC_001416.1:o.100A>G");
    }

    #[test]
    fn test_parse_circular_duplication() {
        // Normal duplication on circular DNA
        let variant = parse_variant("NC_001416.1:o.100_200dup").unwrap();
        assert!(matches!(variant, HgvsVariant::Circular(_)));
        assert_eq!(format!("{}", variant), "NC_001416.1:o.100_200dup");
    }

    #[test]
    fn test_parse_circular_deletion() {
        // Deletion on circular DNA
        let variant = parse_variant("NC_001416.1:o.100_200del").unwrap();
        assert!(matches!(variant, HgvsVariant::Circular(_)));
        assert_eq!(format!("{}", variant), "NC_001416.1:o.100_200del");
    }

    #[test]
    fn test_parse_circular_insertion() {
        let variant = parse_variant("NC_001416.1:o.100_101insATG").unwrap();
        assert!(matches!(variant, HgvsVariant::Circular(_)));
        assert_eq!(format!("{}", variant), "NC_001416.1:o.100_101insATG");
    }

    // === SVD-WG007: RNA Fusion (::) tests ===

    #[test]
    fn test_parse_rna_fusion_basic() {
        // Basic fusion: NM_152263.2:r.-115_775::NM_002609.3:r.1580_*1924
        let variant = parse_variant("NM_152263.2:r.-115_775::NM_002609.3:r.1580_*1924").unwrap();
        assert!(matches!(variant, HgvsVariant::RnaFusion(_)));
        if let HgvsVariant::RnaFusion(fusion) = &variant {
            assert_eq!(fusion.five_prime.accession.full(), "NM_152263.2");
            assert_eq!(fusion.three_prime.accession.full(), "NM_002609.3");
        }
        assert_eq!(
            format!("{}", variant),
            "NM_152263.2:r.-115_775::NM_002609.3:r.1580_*1924"
        );
    }

    #[test]
    fn test_parse_rna_fusion_simple_positions() {
        let variant = parse_variant("NM_000546.5:r.1_200::NM_000245.3:r.100_500").unwrap();
        assert!(matches!(variant, HgvsVariant::RnaFusion(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_000546.5:r.1_200::NM_000245.3:r.100_500"
        );
    }

    #[test]
    fn test_parse_rna_fusion_single_positions() {
        // Fusion with single position on each side
        let variant = parse_variant("NM_000001.1:r.100::NM_000002.1:r.200").unwrap();
        assert!(matches!(variant, HgvsVariant::RnaFusion(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_000001.1:r.100::NM_000002.1:r.200"
        );
    }

    #[test]
    fn test_parse_rna_fusion_epcam_msh2() {
        // Real-world example: EPCAM::MSH2 fusion (Lynch syndrome)
        let variant = parse_variant("NM_002354.2:r.1_3469::NM_000251.2:r.3397_6871").unwrap();
        assert!(matches!(variant, HgvsVariant::RnaFusion(_)));
        if let HgvsVariant::RnaFusion(fusion) = &variant {
            assert_eq!(&*fusion.five_prime.accession.prefix, "NM");
            assert_eq!(&*fusion.three_prime.accession.prefix, "NM");
        }
    }

    // ============== Extended Pattern Coverage Tests ==============

    #[test]
    fn test_parse_nested_repeat_notation() {
        // Genotype notation: A[6][1] - 6 repeats on one allele, 1 on another
        let variant = parse_variant("NM_000088.3:c.100A[6][1]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));

        // Three repeat counts
        let variant = parse_variant("NM_000088.3:c.100[4][5][6]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_complex_insertion_with_parts() {
        // Complex insertion with repeat
        let variant = parse_variant("NM_000088.3:c.100_101ins[A[10];T]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));

        // Complex insertion with position range reference
        let variant = parse_variant("NM_000088.3:c.419_420ins[T;401_419]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_uniprot_protein_variant() {
        // 6-character UniProt accession
        let variant = parse_variant("P54802:p.Phe48Leu").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        if let HgvsVariant::Protein(prot) = &variant {
            assert_eq!(&*prot.accession.prefix, "P");
            assert_eq!(&*prot.accession.number, "54802");
        }

        // Another UniProt accession
        let variant = parse_variant("Q8TAM1:p.Arg34Pro").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
    }

    #[test]
    fn test_parse_uniprot_10char_accession() {
        // 10-character UniProt accession (first char is prefix, rest is number)
        let variant = parse_variant("A0A024R1R8:p.Val100Glu").unwrap();
        assert!(matches!(variant, HgvsVariant::Protein(_)));
        if let HgvsVariant::Protein(prot) = &variant {
            assert_eq!(&*prot.accession.prefix, "A");
            assert_eq!(&*prot.accession.number, "0A024R1R8");
            // Full accession should display correctly
            assert_eq!(prot.accession.full(), "A0A024R1R8");
        }
    }

    #[test]
    fn test_parse_inversion_with_length() {
        // Inversion with explicit length: inv3
        let variant = parse_variant("NM_000088.3:c.274_276inv3").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_inversion_with_sequence() {
        // Inversion with explicit sequence: invATG
        let variant = parse_variant("NM_000088.3:c.274_276invATG").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_uncertain_duplication_range() {
        // Uncertain duplication range: dup(731_741)
        let variant = parse_variant("NM_000088.3:c.722_742dup(731_741)").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));

        // Completely uncertain dup: dup?
        let variant = parse_variant("NM_000088.3:c.100dup?").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));

        // Uncertain dup with parens: dup(?)
        let variant = parse_variant("NM_000088.3:c.100dup(?)").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_assembly_chromosome_notation() {
        // Assembly/chromosome notation
        let variant = parse_variant("GRCh38(chr1):g.100A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        if let HgvsVariant::Genome(gen) = &variant {
            assert!(gen.accession.is_assembly_ref());
            assert_eq!(gen.accession.assembly.as_deref(), Some("GRCh38"));
            assert_eq!(gen.accession.chromosome.as_deref(), Some("chr1"));
        }

        // GRCh37 notation
        let variant = parse_variant("GRCh37(chrX):g.15000del").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
    }

    #[test]
    fn test_parse_circular_dna_notation() {
        // Circular DNA variant (o. prefix)
        let variant = parse_variant("NC_012920.1:o.100A>G").unwrap();
        assert!(matches!(variant, HgvsVariant::Circular(_)));
    }

    #[test]
    fn test_parse_complex_uncertain_positions() {
        // Already tested but verify roundtrip
        let variant = parse_variant("NM_000088.3:c.(?_-1)_328+?del").unwrap();
        assert_eq!(format!("{}", variant), "NM_000088.3:c.(?_-1)_328+?del");

        // Another complex pattern
        let variant = parse_variant("NM_000088.3:c.(?_1)_5074+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
    }

    #[test]
    fn test_parse_unknown_position_patterns() {
        // Unknown position with duplication: c.?dup
        let variant = parse_variant("NM_001412270.1:c.?dup").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_001412270.1:c.?dup");

        // Unknown position with offset at start: c.?-232_4484+?del
        let variant = parse_variant("NM_007294.3:c.?-232_4484+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_007294.3:c.?-232_4484+?del");

        // Same pattern with LRG accession
        let variant = parse_variant("LRG_292t1:c.?-232_4484+?del").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "LRG_292t1:c.?-232_4484+?del");
    }

    #[test]
    fn test_parse_delins_external_reference() {
        // Delins with external GenBank reference
        let variant =
            parse_variant("NC_000008.11:g.86587460_86650711delins[KY923049.1:g.1_466]").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000008.11:g.86587460_86650711delins[KY923049.1:g.1_466]"
        );

        // CDS delins with external reference and intronic positions
        let variant =
            parse_variant("NM_019098.4:c.904-2824_1782-8208delins[KY923049.1:g.1_466]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_019098.4:c.904-2824_1782-8208delins[KY923049.1:g.1_466]"
        );
    }

    #[test]
    fn test_parse_complex_delins_array() {
        // Complex delins with sequence, positions, and inversions
        let variant = parse_variant("NC_000007.14:g.45043702_46521017delins[AGAAGGAAATTT;45310743_46521014;45043709_45310738inv]").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(format!("{}", variant), "NC_000007.14:g.45043702_46521017delins[AGAAGGAAATTT;45310743_46521014;45043709_45310738inv]");

        // Simple complex delins with just inversion
        let variant =
            parse_variant("NC_000016.9:g.78179358_78219143delins[78185355_78199419inv]").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000016.9:g.78179358_78219143delins[78185355_78199419inv]"
        );
    }

    #[test]
    fn test_parse_delins_sequence_repeat_range() {
        // Delins with sequence repeat range: delinsAAAGG[400_2000]
        let variant =
            parse_variant("NC_000004.12:g.39348425_39348479delinsAAAGG[400_2000]").unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000004.12:g.39348425_39348479delinsAAAGG[400_2000]"
        );
    }

    #[test]
    fn test_parse_complex_insertion_with_external() {
        // Complex insertion with literal and external reference: ins[TCTT;KT192064.1:1_310]
        let variant = parse_variant("NM_017635.5:c.438_439ins[TCTT;KT192064.1:1_310]").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(
            format!("{}", variant),
            "NM_017635.5:c.438_439ins[TCTT;KT192064.1:1_310]"
        );
    }

    #[test]
    fn test_parse_telomere_qter_patterns() {
        // Telomere/qter notation - complex structural variants
        // NC_000009.12:g.12891379_qterdelins[T;NC_000020.11:g.47204889_qterinv]
        let variant =
            parse_variant("NC_000009.12:g.12891379_qterdelins[T;NC_000020.11:g.47204889_qterinv]")
                .unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000009.12:g.12891379_qterdelins[T;NC_000020.11:g.47204889_qterinv]"
        );

        // NC_000013.10:g.114819939_qterdelins[96729864_114814234inv;96735632_104289803]
        let variant = parse_variant(
            "NC_000013.10:g.114819939_qterdelins[96729864_114814234inv;96735632_104289803]",
        )
        .unwrap();
        assert!(matches!(variant, HgvsVariant::Genome(_)));
        assert_eq!(
            format!("{}", variant),
            "NC_000013.10:g.114819939_qterdelins[96729864_114814234inv;96735632_104289803]"
        );
    }

    #[test]
    fn test_parse_predicted_substitution_in_parens() {
        // Predicted substitution in parens: c.(9740C>A)
        // This is a predicted variant where the whole edit is wrapped in parentheses
        let variant = parse_variant("NM_002016.2:c.(9740C>A)").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_002016.2:c.9740(C>A)");

        let variant = parse_variant("NM_006767.4:c.(742G>A)").unwrap();
        assert!(matches!(variant, HgvsVariant::Cds(_)));
        assert_eq!(format!("{}", variant), "NM_006767.4:c.742(G>A)");
    }

    #[test]
    fn test_parse_uncertain_intron_exon_ranges() {
        // Uncertain intron/exon ranges - these are complex patterns
        // Pattern 1: c.(2727+1_2728-1)(2858+1_2859-1) - non-standard (no underscore between ranges)
        // Patterns 2 & 3 are position-only (no edit type) which is non-standard HGVS
    }

    #[test]
    fn test_parse_reverse_order_intervals() {
        // Reverse order intervals - where start > end (used for structural variants)
        // Feature 15: Reverse order intervals
        let variant =
            parse_variant("NC_000011.10:g.5238138_5153222insTATTT").expect("should parse");
        assert_eq!(
            variant.to_string(),
            "NC_000011.10:g.5238138_5153222insTATTT"
        );

        let variant = parse_variant("NC_000012.11:g.110593351_110576466dup").expect("should parse");
        assert_eq!(variant.to_string(), "NC_000012.11:g.110593351_110576466dup");

        // Also from Feature 16
        let variant = parse_variant("NC_000016.9:g.23634775_23621090dup").expect("should parse");
        assert_eq!(variant.to_string(), "NC_000016.9:g.23634775_23621090dup");
    }

    #[test]
    fn test_parse_position_only_cds() {
        // Feature 6: Position-Only CDS - positions without edit type
        let variant = parse_variant("NM_173651.4:c.5238_5240").expect("should parse");
        assert_eq!(variant.to_string(), "NM_173651.4:c.5238_5240");

        let variant = parse_variant("NM_134428.2:c.1486_1487").expect("should parse");
        assert_eq!(variant.to_string(), "NM_134428.2:c.1486_1487");

        // 3'UTR position-only
        let variant = parse_variant("NM_007375.3:c.*697").expect("should parse");
        assert_eq!(variant.to_string(), "NM_007375.3:c.*697");
    }

    #[test]
    fn test_parse_unknown_position_insertion() {
        // Unknown position insertion patterns
        // g.?_?ins(start_boundary)_(end_boundary)
        let _result = parse_variant("LRG_308:g.?_?ins(23632682_23625413)_(23625324_23619334)");

        let _result = parse_variant("NG_007406.1:g.?_?ins(23632682_23625413)_(23625324_23619334)");
    }

    #[test]
    fn test_parse_tx_downstream_positions() {
        // Feature 16: n.* downstream positions (after transcript end)
        let variant = parse_variant("NR_033294.1:n.*5C>G").expect("should parse");
        assert_eq!(variant.to_string(), "NR_033294.1:n.*5C>G");

        // With offset
        let variant = parse_variant("NR_033294.1:n.*5+10C>G").expect("should parse");
        assert_eq!(variant.to_string(), "NR_033294.1:n.*5+10C>G");
    }

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

    #[test]
    fn test_parse_self_cancelling_allele_rejected() {
        let result = parse_variant("NM_004006.2:c.[762_768del;767_774dup]");
        assert!(result.is_err(), "self-cancelling allele must be rejected");
        let err = result.unwrap_err();
        assert_eq!(
            err.code(),
            Some(crate::error::ErrorCode::SelfCancellingAllele),
            "rejection must carry E3006"
        );
    }

    #[test]
    fn test_parse_non_overlapping_allele_accepted() {
        // Same edit kinds as the spec example but non-overlapping ranges:
        // OK to coexist.
        let result = parse_variant("NM_004006.2:c.[100_110del;200_210dup]");
        assert!(
            result.is_ok(),
            "non-overlapping del+dup must be accepted: {result:?}"
        );
    }
}