ferro-hgvs 0.4.1

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
//! cdot JSON parsing for transcript alignments.
//!
//! This module handles loading and parsing cdot JSON files which contain
//! transcript-to-genome alignments used for coordinate mapping.
//!
//! Supports both the real cdot format (with nested genome_builds) and
//! a simplified flat format for testing.
//!
//! # Coordinate Systems
//!
//! **IMPORTANT**: cdot uses MIXED coordinate systems!
//!
//! | Field | Basis | Format |
//! |-------|-------|--------|
//! | Genomic coordinates (`genome_start`, `genome_end`) | 0-based | Half-open `[start, end)` |
//! | Transcript coordinates (`tx_start`, `tx_end`) | 1-based | See note below |
//! | CDS coordinates (`cds_start`, `cds_end`) | 0-based | Half-open `[start, end)` |
//!
//! **Note on transcript coordinates**: The cdot format uses 1-based transcript
//! positions (fixed in commit 944a4e9). This is a common source of bugs when
//! developers assume all coordinates are 0-based.
//!
//! For type-safe coordinate handling, see [`crate::coords`].

use crate::error::FerroError;
use crate::liftover::aliases::ContigAliases;
use crate::reference::transcript::GenomeBuild;
use crate::reference::Strand;
use bincode::Options;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::Path;

/// cdot transcript alignment data (normalized internal representation).
///
/// # Coordinate Systems
/// - Genomic: 0-based half-open `[start, end)`
/// - Transcript (tx_start/tx_end in exons): 1-based
/// - CDS: 0-based half-open `[start, end)` in transcript space
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdotTranscript {
    /// Gene name/symbol (e.g., "BRCA1").
    #[serde(default)]
    pub gene_name: Option<String>,

    /// Genomic contig/chromosome (e.g., "NC_000017.11").
    #[serde(alias = "contig", alias = "chr")]
    pub contig: String,

    /// Strand (+ or -).
    #[serde(deserialize_with = "deserialize_strand")]
    pub strand: Strand,

    /// Exon alignments: [genome_start(0-based), genome_end(0-based excl), tx_start(1-based), tx_end(1-based)].
    pub exons: Vec<[u64; 4]>,

    /// Start of CDS in transcript coordinates (0-based, inclusive).
    #[serde(default)]
    pub cds_start: Option<u64>,

    /// End of CDS in transcript coordinates (0-based, exclusive).
    #[serde(default)]
    pub cds_end: Option<u64>,

    /// Per-exon CIGAR alignment data from cdot gap info (GFF3 Gap format).
    /// Indexed in the same order as `exons` (sorted by tx position).
    #[serde(skip)]
    pub exon_cigars: Vec<Option<Vec<CigarOp>>>,

    /// Gene ID (e.g., "HGNC:1100").
    #[serde(default)]
    pub gene_id: Option<String>,

    /// Protein accession (e.g., "NP_000079.2").
    #[serde(default)]
    pub protein: Option<String>,
}

/// Raw cdot transcript entry as it appears in the JSON file.
/// The real cdot format nests genome-specific data under genome_builds.
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] // Fields used for serde deserialization
struct RawCdotTranscript {
    #[serde(default)]
    gene_name: Option<String>,
    #[serde(default)]
    gene_version: Option<String>,
    #[serde(default)]
    biotype: Option<Vec<String>>,
    #[serde(default)]
    genome_builds: Option<HashMap<String, RawGenomeBuild>>,
    /// CDS start in transcript coordinates (0-indexed)
    #[serde(default)]
    start_codon: Option<u64>,
    /// CDS end in transcript coordinates (0-indexed, exclusive)
    #[serde(default)]
    stop_codon: Option<u64>,
    // Flat format fields (for backwards compatibility)
    #[serde(default)]
    contig: Option<String>,
    #[serde(default)]
    strand: Option<String>,
    #[serde(default)]
    exons: Option<Vec<Vec<serde_json::Value>>>,
    #[serde(default)]
    cds_start: Option<u64>,
    #[serde(default)]
    cds_end: Option<u64>,
}

/// Genome build specific data in cdot format.
#[derive(Debug, Clone, Deserialize)]
struct RawGenomeBuild {
    contig: String,
    #[serde(default)]
    strand: Option<String>,
    /// Exons in cdot format: [genomic_start, genomic_end, exon_num, tx_start, tx_end, gap_info]
    exons: Vec<Vec<serde_json::Value>>,
    /// CDS start in genomic coordinates
    #[serde(default)]
    cds_start: Option<u64>,
    /// CDS end in genomic coordinates
    #[serde(default)]
    cds_end: Option<u64>,
}

impl RawCdotTranscript {
    /// Convert raw transcript to internal format for a specific genome build.
    fn to_transcript(&self, genome_build: &str) -> Option<CdotTranscript> {
        // Try genome_builds first (real cdot format)
        if let Some(builds) = &self.genome_builds {
            if let Some(build) = builds.get(genome_build) {
                return self.from_genome_build(build);
            }
        }

        // Fall back to flat format
        self.from_flat_format()
    }

    /// Convert from nested genome_builds format.
    #[allow(clippy::wrong_self_convention)]
    fn from_genome_build(&self, build: &RawGenomeBuild) -> Option<CdotTranscript> {
        let strand = parse_strand(build.strand.as_deref().unwrap_or("+"))?;

        // Parse exons: [genomic_start, genomic_end, exon_num, tx_start, tx_end, gap_info]
        let mut exon_pairs: Vec<([u64; 4], Option<Vec<CigarOp>>)> = build
            .exons
            .iter()
            .filter_map(|e| {
                if e.len() >= 5 {
                    let exon = [
                        e[0].as_u64()?,
                        e[1].as_u64()?,
                        e[3].as_u64()?, // tx_start is at index 3
                        e[4].as_u64()?, // tx_end is at index 4
                    ];
                    // Parse CIGAR gap info from index 5 if present
                    let cigar = if e.len() > 5 {
                        e[5].as_str().and_then(|s| match parse_cigar(s) {
                            Ok(ops) => Some(ops),
                            Err(err) => {
                                log::warn!("Malformed CIGAR string '{}': {}", s, err);
                                None
                            }
                        })
                    } else {
                        None
                    };
                    Some((exon, cigar))
                } else {
                    None
                }
            })
            .collect();

        // Sort exons by transcript position, keeping CIGARs in sync
        exon_pairs.sort_by_key(|(e, _)| e[2]);
        let (exons, exon_cigars): (Vec<[u64; 4]>, Vec<Option<Vec<CigarOp>>>) =
            exon_pairs.into_iter().unzip();

        // Use transcript-level CDS coordinates (start_codon/stop_codon) if available
        // These are 0-indexed and more reliable than converting from genomic coords
        let (cds_start, cds_end) = if self.start_codon.is_some() || self.stop_codon.is_some() {
            // Use transcript-level coordinates directly (0-indexed)
            (self.start_codon, self.stop_codon)
        } else {
            // Fall back to converting genomic CDS coordinates to transcript coordinates
            match (build.cds_start, build.cds_end) {
                (Some(g_start), Some(g_end)) => {
                    // Find transcript positions for genomic CDS boundaries
                    let tx_cds_start = genomic_to_tx_pos(&exons, g_start, strand);
                    let tx_cds_end = genomic_to_tx_pos(&exons, g_end, strand);

                    match (tx_cds_start, tx_cds_end) {
                        (Some(s), Some(e)) => {
                            // CDS end is exclusive, so add 1
                            // Use saturating_add to prevent overflow at u64::MAX
                            let (start, end) = if s < e {
                                (s, e.saturating_add(1))
                            } else {
                                (e, s.saturating_add(1))
                            };
                            (Some(start), Some(end))
                        }
                        _ => (None, None),
                    }
                }
                _ => (None, None),
            }
        };

        Some(CdotTranscript {
            gene_name: self.gene_name.clone(),
            contig: build.contig.clone(),
            strand,
            exons,
            exon_cigars,
            cds_start,
            cds_end,
            gene_id: None,
            protein: None,
        })
    }

    /// Convert from flat format (for backwards compatibility).
    #[allow(clippy::wrong_self_convention)]
    fn from_flat_format(&self) -> Option<CdotTranscript> {
        let contig = self.contig.as_ref()?.clone();
        let strand = parse_strand(self.strand.as_deref().unwrap_or("+"))?;

        let exons: Vec<[u64; 4]> = self
            .exons
            .as_ref()?
            .iter()
            .filter_map(|e| {
                if e.len() >= 4 {
                    Some([
                        e[0].as_u64()?,
                        e[1].as_u64()?,
                        e[2].as_u64()?,
                        e[3].as_u64()?,
                    ])
                } else {
                    None
                }
            })
            .collect();

        Some(CdotTranscript {
            gene_name: self.gene_name.clone(),
            contig,
            strand,
            exon_cigars: Vec::new(),
            exons,
            cds_start: self.cds_start,
            cds_end: self.cds_end,
            gene_id: None,
            protein: None,
        })
    }
}

/// Parse strand string to Strand enum.
fn parse_strand(s: &str) -> Option<Strand> {
    match s {
        "+" | "1" | "plus" => Some(Strand::Plus),
        "-" | "-1" | "minus" => Some(Strand::Minus),
        _ => None,
    }
}

/// Convert genomic position to transcript position using exon data.
fn genomic_to_tx_pos(exons: &[[u64; 4]], genomic_pos: u64, strand: Strand) -> Option<u64> {
    for e in exons {
        let (g_start, g_end, tx_start, _tx_end) = (e[0], e[1], e[2], e[3]);
        if genomic_pos >= g_start && genomic_pos < g_end {
            let offset = match strand {
                Strand::Plus => genomic_pos - g_start,
                Strand::Minus => g_end - 1 - genomic_pos,
            };
            return Some(tx_start + offset);
        }
    }
    // Position not in an exon - find closest exon boundary
    // This handles CDS boundaries that might be at intron edges
    for e in exons {
        let (g_start, g_end, tx_start, tx_end) = (e[0], e[1], e[2], e[3]);
        if genomic_pos == g_end {
            return Some(tx_end);
        }
        if genomic_pos == g_start.saturating_sub(1) {
            return Some(tx_start.saturating_sub(1));
        }
    }
    None
}

/// Deserialize strand from string.
fn deserialize_strand<'de, D>(deserializer: D) -> Result<Strand, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    match s.as_str() {
        "+" | "1" | "plus" => Ok(Strand::Plus),
        "-" | "-1" | "minus" => Ok(Strand::Minus),
        _ => Err(serde::de::Error::custom(format!("Invalid strand: {}", s))),
    }
}

/// Parsed exon with named fields for clarity.
///
/// # Coordinate Systems
/// - Genomic coordinates: 0-based half-open `[genome_start, genome_end)`
/// - Transcript coordinates: 1-based (NOT 0-based - common source of bugs!)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exon {
    /// Exon number (1-based).
    pub number: u32,
    /// Start position in genomic coordinates (0-based, inclusive).
    pub genome_start: u64,
    /// End position in genomic coordinates (0-based, exclusive).
    pub genome_end: u64,
    /// Start position in transcript coordinates (1-based, inclusive).
    pub tx_start: u64,
    /// End position in transcript coordinates (1-based, exclusive for range).
    pub tx_end: u64,
}

impl Exon {
    /// Create an exon from cdot array format.
    pub fn from_array(number: u32, arr: [u64; 4]) -> Self {
        Self {
            number,
            genome_start: arr[0],
            genome_end: arr[1],
            tx_start: arr[2],
            tx_end: arr[3],
        }
    }

    /// Get the length of this exon.
    pub fn len(&self) -> u64 {
        self.genome_end - self.genome_start
    }

    /// Check if the exon is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Check if a genomic position is within this exon.
    pub fn contains_genome_pos(&self, pos: u64) -> bool {
        pos >= self.genome_start && pos < self.genome_end
    }

    /// Check if a transcript position is within this exon.
    pub fn contains_tx_pos(&self, pos: u64) -> bool {
        pos >= self.tx_start && pos < self.tx_end
    }
}

impl CdotTranscript {
    /// Get exons as structured objects.
    pub fn get_exons(&self) -> Vec<Exon> {
        self.exons
            .iter()
            .enumerate()
            .map(|(i, arr)| Exon::from_array((i + 1) as u32, *arr))
            .collect()
    }

    /// Get total transcript length (sum of exon lengths).
    pub fn transcript_length(&self) -> u64 {
        self.exons.iter().map(|e| e[3] - e[2]).sum()
    }

    /// Get CDS length if CDS is defined.
    pub fn cds_length(&self) -> Option<u64> {
        match (self.cds_start, self.cds_end) {
            (Some(start), Some(end)) => Some(end - start),
            _ => None,
        }
    }

    /// Find exon containing a transcript position.
    pub fn exon_for_tx_pos(&self, tx_pos: u64) -> Option<Exon> {
        for (i, arr) in self.exons.iter().enumerate() {
            if tx_pos >= arr[2] && tx_pos < arr[3] {
                return Some(Exon::from_array((i + 1) as u32, *arr));
            }
        }
        None
    }

    /// Find exon containing a genomic position.
    pub fn exon_for_genome_pos(&self, genome_pos: u64) -> Option<Exon> {
        for (i, arr) in self.exons.iter().enumerate() {
            if genome_pos >= arr[0] && genome_pos < arr[1] {
                return Some(Exon::from_array((i + 1) as u32, *arr));
            }
        }
        None
    }

    /// Convert transcript position to genomic position.
    pub fn tx_to_genome(&self, tx_pos: u64) -> Option<u64> {
        let exon = self.exon_for_tx_pos(tx_pos)?;
        let offset = tx_pos - exon.tx_start;

        match self.strand {
            Strand::Plus => Some(exon.genome_start + offset),
            Strand::Minus => Some(exon.genome_end - 1 - offset),
        }
    }

    /// Convert genomic position to transcript position.
    pub fn genome_to_tx(&self, genome_pos: u64) -> Option<u64> {
        let exon = self.exon_for_genome_pos(genome_pos)?;

        match self.strand {
            Strand::Plus => {
                let offset = genome_pos - exon.genome_start;
                Some(exon.tx_start + offset)
            }
            Strand::Minus => {
                let offset = exon.genome_end - 1 - genome_pos;
                Some(exon.tx_start + offset)
            }
        }
    }

    /// Convert CDS position (1-based) to transcript position (0-based).
    pub fn cds_to_tx(&self, cds_pos: i64) -> Option<u64> {
        let cds_start = self.cds_start?;

        if cds_pos > 0 {
            // Normal CDS position
            Some(cds_start + (cds_pos as u64 - 1))
        } else if cds_pos < 0 {
            // 5' UTR position (e.g., c.-100)
            let offset = (-cds_pos) as u64;
            if offset <= cds_start {
                Some(cds_start - offset)
            } else {
                None // Beyond transcript start
            }
        } else {
            None // Position 0 is not valid
        }
    }

    /// Convert transcript position (0-based) to CDS position (1-based).
    pub fn tx_to_cds(&self, tx_pos: u64) -> Option<CdsPosition> {
        let cds_start = self.cds_start?;
        let cds_end = self.cds_end?;

        if tx_pos < cds_start {
            // 5' UTR
            let offset = cds_start - tx_pos;
            Some(CdsPosition::FivePrimeUtr(offset as i64))
        } else if tx_pos < cds_end {
            // CDS
            let cds_pos = tx_pos - cds_start + 1;
            Some(CdsPosition::Cds(cds_pos as i64))
        } else {
            // 3' UTR
            let offset = tx_pos - cds_end + 1;
            Some(CdsPosition::ThreePrimeUtr(offset as i64))
        }
    }

    /// Get the intron number for a genomic position.
    /// Returns None if the position is within an exon.
    pub fn intron_for_genome_pos(&self, genome_pos: u64) -> Option<(u32, i64)> {
        let exons = self.get_exons();

        for i in 0..exons.len().saturating_sub(1) {
            let current = &exons[i];
            let next = &exons[i + 1];

            let (intron_start, intron_end) = match self.strand {
                Strand::Plus => (current.genome_end, next.genome_start),
                Strand::Minus => (next.genome_end, current.genome_start),
            };

            if genome_pos >= intron_start && genome_pos < intron_end {
                let intron_num = (i + 1) as u32;
                let offset = match self.strand {
                    Strand::Plus => (genome_pos as i64) - (current.genome_end as i64),
                    Strand::Minus => (current.genome_start as i64) - (genome_pos as i64),
                };
                // Adjust for 0-based to intronic offset convention
                let intronic_offset = if offset >= 0 { offset + 1 } else { offset };
                return Some((intron_num, intronic_offset));
            }
        }

        None
    }
}

/// CDS position type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CdsPosition {
    /// Position in 5' UTR (e.g., c.-100 would be FivePrimeUtr(100)).
    FivePrimeUtr(i64),
    /// Normal CDS position (1-based).
    Cds(i64),
    /// Position in 3' UTR (e.g., c.*100 would be ThreePrimeUtr(100)).
    ThreePrimeUtr(i64),
}

/// A single CIGAR operation from a GFF3 Gap attribute string.
///
/// cdot uses GFF3 Gap format (letter-first, space-separated), e.g. `M185 I3 M250`,
/// which differs from SAM CIGAR format (`185M3I250M`).
///
/// - `M` (Match): alignment match — bases align between transcript and genome.
/// - `I` (Insertion): bases present in the transcript but not the genome.
/// - `D` (Deletion): bases present in the genome but not the transcript.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CigarOp {
    /// Alignment match of `n` bases.
    Match(u64),
    /// Insertion of `n` bases in the transcript (not in genome).
    Insertion(u64),
    /// Deletion of `n` bases from the transcript (present in genome).
    Deletion(u64),
}

/// Parse a GFF3 Gap attribute string into a sequence of CIGAR operations.
///
/// The format is space-separated tokens, each starting with an operation letter
/// (`M`, `I`, or `D`) followed by a length, e.g. `"M185 I3 M250"`.
///
/// Returns an empty vector for empty or whitespace-only input.
///
/// # Errors
///
/// Returns an error if a token has an unrecognized operation letter or a non-numeric length.
pub fn parse_cigar(cigar_str: &str) -> Result<Vec<CigarOp>, FerroError> {
    let trimmed = cigar_str.trim();
    if trimmed.is_empty() {
        return Ok(Vec::new());
    }

    trimmed
        .split_whitespace()
        .map(|token| {
            if token.len() < 2 {
                return Err(FerroError::parse(
                    0,
                    format!("Invalid CIGAR token (too short): \'{token}\'"),
                ));
            }
            let (op_char, len_str) = token.split_at(1);
            let length: u64 = len_str.parse().map_err(|_| {
                FerroError::parse(0, format!("Invalid CIGAR length in token: \'{token}\'"))
            })?;
            match op_char {
                "M" => Ok(CigarOp::Match(length)),
                "I" => Ok(CigarOp::Insertion(length)),
                "D" => Ok(CigarOp::Deletion(length)),
                _ => Err(FerroError::parse(
                    0,
                    format!("Unknown CIGAR operation \'{op_char}\' in token: \'{token}\'"),
                )),
            }
        })
        .collect()
}

/// Compute the cumulative insertion offset at a given 1-based transcript position.
///
/// Walks through the CIGAR operations and counts insertion bases that occur
/// before `tx_pos`. Insertions add bases to the transcript that do not exist
/// in the genome, so CDS numbering (which follows the genome) must account
/// for them.
///
/// Returns the total number of insertion bases encountered before `tx_pos`.
pub fn cumulative_insertion_offset(ops: &[CigarOp], tx_pos: u64) -> u64 {
    let mut current_tx: u64 = 0;
    let mut cumulative: u64 = 0;

    for op in ops {
        match op {
            CigarOp::Match(len) => {
                current_tx += len;
            }
            CigarOp::Insertion(len) => {
                // If the entire insertion is before tx_pos, count it all
                if current_tx + len <= tx_pos {
                    cumulative += len;
                }
                current_tx += len;
            }
            CigarOp::Deletion(_) => {
                // Deletions don't advance the transcript position
            }
        }
        if current_tx >= tx_pos {
            break;
        }
    }

    cumulative
}

/// Raw cdot JSON file structure (as it appears on disk).
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)] // Fields used for serde deserialization
struct RawCdotFile {
    /// Transcripts indexed by accession (raw format).
    transcripts: HashMap<String, RawCdotTranscript>,

    /// Genome builds available (list, e.g., ["GRCh38"])
    #[serde(default)]
    genome_builds: Option<Vec<String>>,

    /// cdot version
    #[serde(default)]
    cdot_version: Option<String>,

    /// Gene information (we ignore this for now)
    #[serde(default)]
    genes: Option<serde_json::Value>,

    /// Metadata (we ignore this for now)
    #[serde(default)]
    metadata: Option<serde_json::Value>,
}

/// cdot JSON file structure (normalized for internal use).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CdotFile {
    /// Transcripts indexed by accession.
    pub transcripts: HashMap<String, CdotTranscript>,

    /// Genome builds information (optional).
    #[serde(default)]
    pub genome_builds: Option<HashMap<String, serde_json::Value>>,
}

/// Bincode-friendly snapshot of CdotMapper data, without custom JSON deserializers.
/// Used for deserialization only; serialization uses [`CdotMapperSnapshotRef`].
#[derive(Deserialize)]
struct CdotMapperSnapshot {
    transcripts: HashMap<String, CdotTranscriptSnapshot>,
    contig_index: HashMap<String, Vec<String>>,
    contig_alias_to_canonical: HashMap<String, String>,
    base_to_versioned: HashMap<String, String>,
    lrg_to_refseq: HashMap<String, String>,
}

/// Borrowed view of CdotMapper for zero-copy serialization to bincode.
#[derive(Serialize)]
struct CdotMapperSnapshotRef<'a> {
    transcripts: HashMap<&'a String, CdotTranscriptSnapshotRef<'a>>,
    contig_index: &'a HashMap<String, Vec<String>>,
    contig_alias_to_canonical: &'a HashMap<String, String>,
    base_to_versioned: &'a HashMap<String, String>,
    lrg_to_refseq: &'a HashMap<String, String>,
}

/// Bincode-friendly snapshot of CdotTranscript, using standard Strand serde.
/// Used for deserialization only; serialization uses [`CdotTranscriptSnapshotRef`].
#[derive(Deserialize)]
struct CdotTranscriptSnapshot {
    gene_name: Option<String>,
    contig: String,
    strand: Strand,
    exons: Vec<[u64; 4]>,
    cds_start: Option<u64>,
    cds_end: Option<u64>,
    exon_cigars: Vec<Option<Vec<CigarOp>>>,
    gene_id: Option<String>,
    protein: Option<String>,
}

/// Borrowed view of CdotTranscript for zero-copy serialization to bincode.
#[derive(Serialize)]
struct CdotTranscriptSnapshotRef<'a> {
    gene_name: &'a Option<String>,
    contig: &'a str,
    strand: Strand,
    exons: &'a Vec<[u64; 4]>,
    cds_start: Option<u64>,
    cds_end: Option<u64>,
    exon_cigars: &'a Vec<Option<Vec<CigarOp>>>,
    gene_id: &'a Option<String>,
    protein: &'a Option<String>,
}

impl<'a> From<&'a CdotTranscript> for CdotTranscriptSnapshotRef<'a> {
    fn from(tx: &'a CdotTranscript) -> Self {
        Self {
            gene_name: &tx.gene_name,
            contig: &tx.contig,
            strand: tx.strand,
            exons: &tx.exons,
            cds_start: tx.cds_start,
            cds_end: tx.cds_end,
            exon_cigars: &tx.exon_cigars,
            gene_id: &tx.gene_id,
            protein: &tx.protein,
        }
    }
}

impl From<CdotTranscriptSnapshot> for CdotTranscript {
    fn from(snap: CdotTranscriptSnapshot) -> Self {
        Self {
            gene_name: snap.gene_name,
            contig: snap.contig,
            strand: snap.strand,
            exons: snap.exons,
            cds_start: snap.cds_start,
            cds_end: snap.cds_end,
            exon_cigars: snap.exon_cigars,
            gene_id: snap.gene_id,
            protein: snap.protein,
        }
    }
}

/// Coordinate mapper using cdot data.
#[derive(Debug, Clone)]
pub struct CdotMapper {
    /// Transcripts indexed by accession.
    transcripts: HashMap<String, CdotTranscript>,
    /// Index from contig to transcript IDs that overlap.
    contig_index: HashMap<String, Vec<String>>,
    /// Alias-to-canonical contig name mapping (e.g., "chr7" -> "NC_000007.14").
    /// Allows lookups by UCSC-style names when `contig_index` keys are RefSeq accessions.
    contig_alias_to_canonical: HashMap<String, String>,
    /// Index from base accession (without version) to versioned accession.
    base_to_versioned: HashMap<String, String>,
    /// LRG transcript to RefSeq transcript mapping (e.g., "LRG_1t1" -> "NM_000088.3").
    lrg_to_refseq: HashMap<String, String>,
}

impl CdotMapper {
    /// Create a new empty mapper.
    pub fn new() -> Self {
        Self {
            transcripts: HashMap::new(),
            contig_index: HashMap::new(),
            contig_alias_to_canonical: HashMap::new(),
            base_to_versioned: HashMap::new(),
            lrg_to_refseq: HashMap::new(),
        }
    }

    /// Load from a cdot JSON file.
    pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot file: {}", e),
        })?;
        let reader = BufReader::new(file);
        Self::from_reader(reader)
    }

    /// Load from a gzip-compressed cdot JSON file.
    pub fn from_json_gz<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot file: {}", e),
        })?;
        let reader = BufReader::new(file);
        let decoder = flate2::read::GzDecoder::new(reader);
        let reader = BufReader::new(decoder);
        Self::from_reader(reader)
    }

    /// Load from a pre-serialized bincode file (much faster than JSON).
    pub fn from_bincode_file<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open cdot bincode file: {}", e),
        })?;
        let file_size = file.metadata().map(|m| m.len()).unwrap_or(0);
        let reader = BufReader::new(file);
        // Use a size limit to prevent OOM on corrupt files. Allow 20x the file size
        // (bincode is compact, but deserialized HashMap overhead can be significant).
        // Limit deserialization size to prevent OOM on corrupt files (20x file size or 1MB min).
        let size_limit = file_size.saturating_mul(20).max(1024 * 1024);
        let snapshot: CdotMapperSnapshot = bincode::options()
            .with_fixint_encoding()
            .allow_trailing_bytes()
            .with_limit(size_limit)
            .deserialize_from(reader)
            .map_err(|e| FerroError::Io {
                msg: format!("Failed to deserialize cdot bincode: {}", e),
            })?;
        Ok(Self {
            transcripts: snapshot
                .transcripts
                .into_iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            contig_index: snapshot.contig_index,
            contig_alias_to_canonical: snapshot.contig_alias_to_canonical,
            base_to_versioned: snapshot.base_to_versioned,
            lrg_to_refseq: snapshot.lrg_to_refseq,
        })
    }

    /// Write the mapper to a bincode file for fast subsequent loading.
    pub fn to_bincode_file<P: AsRef<Path>>(&self, path: P) -> Result<(), FerroError> {
        let snapshot = CdotMapperSnapshotRef {
            transcripts: self
                .transcripts
                .iter()
                .map(|(k, v)| (k, v.into()))
                .collect(),
            contig_index: &self.contig_index,
            contig_alias_to_canonical: &self.contig_alias_to_canonical,
            base_to_versioned: &self.base_to_versioned,
            lrg_to_refseq: &self.lrg_to_refseq,
        };
        let file = File::create(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to create cdot bincode file: {}", e),
        })?;
        let writer = std::io::BufWriter::new(file);
        bincode::options()
            .with_fixint_encoding()
            .serialize_into(writer, &snapshot)
            .map_err(|e| FerroError::Io {
                msg: format!("Failed to serialize cdot bincode: {}", e),
            })
    }

    /// Load a cdot file, preferring a sibling `.bin` (bincode) file if available.
    ///
    /// Given a path to a `.json` or `.json.gz` file, checks for a `.bin` file in the
    /// same directory. If the bincode file exists, loads from it (much faster). Otherwise
    /// falls back to JSON parsing. Also handles `.bin` paths directly.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, FerroError> {
        let path = path.as_ref();
        let path_str = path.to_string_lossy();

        // Direct bincode path — no JSON fallback available
        if path_str.ends_with(".bin") {
            return Self::from_bincode_file(path);
        }

        // Compute the canonical sibling .bin path:
        // - foo.json.gz -> foo.bin (strip .gz then replace .json with .bin)
        // - foo.json    -> foo.bin
        let bin_path = if path_str.ends_with(".json.gz") {
            path.with_extension("").with_extension("bin")
        } else {
            path.with_extension("bin")
        };
        if bin_path.exists() {
            match Self::from_bincode_file(&bin_path) {
                Ok(mapper) => return Ok(mapper),
                Err(e) => {
                    log::warn!(
                        "Failed to load bincode {}: {}. Falling back to JSON.",
                        bin_path.display(),
                        e
                    );
                }
            }
        }

        // Fall back to JSON
        if path_str.ends_with(".gz") {
            Self::from_json_gz(path)
        } else {
            Self::from_json_file(path)
        }
    }

    /// Load from any reader, defaulting to GRCh38 genome build.
    pub fn from_reader<R: Read>(reader: R) -> Result<Self, FerroError> {
        Self::from_reader_with_build(reader, "GRCh38")
    }

    /// Load from any reader with a specific genome build.
    pub fn from_reader_with_build<R: Read>(
        reader: R,
        genome_build: &str,
    ) -> Result<Self, FerroError> {
        let raw_file: RawCdotFile = serde_json::from_reader(reader)?;
        Ok(Self::from_raw_cdot_file(raw_file, genome_build))
    }

    /// Create from a raw CdotFile, converting to internal format.
    fn from_raw_cdot_file(raw_file: RawCdotFile, genome_build: &str) -> Self {
        let mut mapper = Self::new();

        for (accession, raw_transcript) in raw_file.transcripts {
            if let Some(transcript) = raw_transcript.to_transcript(genome_build) {
                mapper.add_transcript(accession, transcript);
            }
        }

        mapper.populate_contig_aliases(genome_build);

        mapper
    }

    /// Create from a parsed CdotFile (already normalized), defaulting to GRCh38 aliases.
    pub fn from_cdot_file(cdot_file: CdotFile) -> Self {
        Self::from_cdot_file_with_build(cdot_file, "GRCh38")
    }

    /// Create from a parsed CdotFile with a specific genome build for contig aliases.
    pub fn from_cdot_file_with_build(cdot_file: CdotFile, genome_build: &str) -> Self {
        let mut mapper = Self::new();

        for (accession, transcript) in cdot_file.transcripts {
            mapper.add_transcript(accession, transcript);
        }

        mapper.populate_contig_aliases(genome_build);

        mapper
    }

    /// Add a transcript to the mapper.
    pub fn add_transcript(&mut self, accession: String, transcript: CdotTranscript) {
        // Update contig index
        self.contig_index
            .entry(transcript.contig.clone())
            .or_default()
            .push(accession.clone());

        // Update base to versioned index (e.g., "NM_000088" -> "NM_000088.4")
        if let Some(base) = accession.split('.').next() {
            self.base_to_versioned
                .insert(base.to_string(), accession.clone());
        }

        self.transcripts.insert(accession, transcript);
    }

    /// Build contig alias mappings from `ContigAliases` so that UCSC-style names
    /// (e.g., "chr7") resolve to the RefSeq accessions used as `contig_index` keys.
    fn populate_contig_aliases(&mut self, genome_build: &str) {
        let build = match genome_build {
            "GRCh37" => GenomeBuild::GRCh37,
            "GRCh38" => GenomeBuild::GRCh38,
            _ => {
                log::warn!(
                    "Unsupported genome build '{}'; contig alias resolution is disabled",
                    genome_build
                );
                return;
            }
        };

        let aliases = ContigAliases::default_human();
        for refseq_contig in self.contig_index.keys() {
            // Map UCSC alias (e.g., "chr7") -> RefSeq key (e.g., "NC_000007.14")
            if let Some(ucsc) = aliases.refseq_to_ucsc(refseq_contig) {
                self.contig_alias_to_canonical
                    .insert(ucsc.to_string(), refseq_contig.clone());
            }
            // Map Ensembl alias (e.g., "7") -> RefSeq key
            if let Some(ensembl) = aliases.refseq_to_ensembl(refseq_contig) {
                self.contig_alias_to_canonical
                    .insert(ensembl.to_string(), refseq_contig.clone());
            }
            // Also allow lookup by the other build's RefSeq accession via resolve
            // (e.g., if someone passes "NC_000007.13" but data is GRCh38)
            // This is handled implicitly since we only index contigs present in the data.
        }

        // Also map any non-RefSeq contig_index keys back through to_refseq
        // in case the cdot data itself uses UCSC names.
        let ucsc_keys: Vec<String> = self
            .contig_index
            .keys()
            .filter(|k| k.starts_with("chr"))
            .cloned()
            .collect();
        for ucsc_key in ucsc_keys {
            if let Some(refseq) = aliases.resolve_to_refseq(&ucsc_key, build) {
                self.contig_alias_to_canonical
                    .insert(refseq.to_string(), ucsc_key.clone());
            }
        }
    }

    /// Resolve a contig name through aliases, returning the canonical key used in `contig_index`.
    fn resolve_contig<'a>(&'a self, contig: &'a str) -> &'a str {
        if self.contig_index.contains_key(contig) {
            contig
        } else {
            self.contig_alias_to_canonical
                .get(contig)
                .map(|s| s.as_str())
                .unwrap_or(contig)
        }
    }

    /// Load LRG to RefSeq transcript mapping from a file.
    ///
    /// The file format is tab-separated with columns:
    /// LRG, HGNC_SYMBOL, REFSEQ_GENOMIC, LRG_TRANSCRIPT, REFSEQ_TRANSCRIPT, ENSEMBL_TRANSCRIPT, CCDS
    ///
    /// This creates mappings like "LRG_1t1" -> "NM_000088.3".
    pub fn load_lrg_mapping<P: AsRef<Path>>(&mut self, path: P) -> Result<usize, FerroError> {
        use std::io::BufRead;

        let file = File::open(path.as_ref()).map_err(|e| FerroError::Io {
            msg: format!("Failed to open LRG mapping file: {}", e),
        })?;
        let reader = std::io::BufReader::new(file);

        let mut count = 0;
        for line in reader.lines() {
            let line = line.map_err(|e| FerroError::Io {
                msg: format!("Failed to read LRG mapping line: {}", e),
            })?;

            // Skip comments and empty lines
            if line.starts_with('#') || line.trim().is_empty() {
                continue;
            }

            let fields: Vec<&str> = line.split('\t').collect();
            if fields.len() < 5 {
                continue;
            }

            // Fields: LRG, HGNC_SYMBOL, REFSEQ_GENOMIC, LRG_TRANSCRIPT, REFSEQ_TRANSCRIPT
            let lrg_id = fields[0]; // e.g., "LRG_1"
            let lrg_transcript = fields[3]; // e.g., "t1"
            let refseq_transcript = fields[4]; // e.g., "NM_000088.3"

            // Skip if RefSeq transcript is empty or "-"
            if refseq_transcript.is_empty() || refseq_transcript == "-" {
                continue;
            }

            // Create full LRG transcript ID: "LRG_1t1"
            let lrg_full = format!("{}{}", lrg_id, lrg_transcript);
            self.lrg_to_refseq
                .insert(lrg_full, refseq_transcript.to_string());
            count += 1;
        }

        Ok(count)
    }

    /// Get the RefSeq transcript ID for an LRG transcript.
    pub fn get_refseq_for_lrg(&self, lrg_accession: &str) -> Option<&str> {
        self.lrg_to_refseq.get(lrg_accession).map(|s| s.as_str())
    }

    /// Get a transcript by accession.
    ///
    /// For LRG transcripts (e.g., "LRG_1t1"), this will look up the equivalent
    /// RefSeq transcript if an LRG mapping has been loaded.
    ///
    /// Supports version fallback: if "NM_000088.2" is not found but "NM_000088.3"
    /// exists, the latter will be returned.
    pub fn get_transcript(&self, accession: &str) -> Option<&CdotTranscript> {
        // First try direct lookup
        if let Some(tx) = self.transcripts.get(accession) {
            return Some(tx);
        }

        // Try version fallback (e.g., NM_000088.2 -> NM_000088.3)
        if let Some(base) = accession.split('.').next() {
            if let Some(versioned) = self.base_to_versioned.get(base) {
                if let Some(tx) = self.transcripts.get(versioned) {
                    return Some(tx);
                }
            }
        }

        // For LRG transcripts, try to find via RefSeq mapping
        if accession.starts_with("LRG_") {
            if let Some(refseq) = self.lrg_to_refseq.get(accession) {
                // Try direct lookup of RefSeq
                if let Some(tx) = self.transcripts.get(refseq) {
                    return Some(tx);
                }
                // Try version fallback for RefSeq too
                if let Some(base) = refseq.split('.').next() {
                    if let Some(versioned) = self.base_to_versioned.get(base) {
                        if let Some(tx) = self.transcripts.get(versioned) {
                            return Some(tx);
                        }
                    }
                }
            }
        }

        None
    }

    /// Get all transcripts on a contig. Resolves aliases (e.g., "chr7" -> "NC_000007.14").
    pub fn transcripts_on_contig(&self, contig: &str) -> Vec<&str> {
        self.contig_index
            .get(self.resolve_contig(contig))
            .map(|ids| ids.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// Find transcripts overlapping a genomic position. Resolves contig aliases.
    pub fn transcripts_at_position(&self, contig: &str, pos: u64) -> Vec<(&str, &CdotTranscript)> {
        self.contig_index
            .get(self.resolve_contig(contig))
            .map(|ids| {
                ids.iter()
                    .filter_map(|id| {
                        let tx = self.transcripts.get(id)?;
                        // Check if position is within transcript genomic range
                        let (min, max) = tx.exons.iter().fold((u64::MAX, 0), |(min, max), e| {
                            (min.min(e[0]), max.max(e[1]))
                        });
                        if pos >= min && pos < max {
                            Some((id.as_str(), tx))
                        } else {
                            None
                        }
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Get the number of transcripts loaded.
    pub fn transcript_count(&self) -> usize {
        self.transcripts.len()
    }

    /// Get all transcript accessions.
    pub fn transcript_ids(&self) -> impl Iterator<Item = &str> {
        self.transcripts.keys().map(|s| s.as_str())
    }
}

impl Default for CdotMapper {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn sample_transcript() -> CdotTranscript {
        // Simple transcript with 3 exons on + strand
        // Exons: [genome_start, genome_end, tx_start, tx_end]
        CdotTranscript {
            gene_name: Some("TEST".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Plus,
            exons: vec![
                [1000, 1100, 0, 100],   // Exon 1: 100bp
                [2000, 2200, 100, 300], // Exon 2: 200bp
                [3000, 3150, 300, 450], // Exon 3: 150bp
            ],
            cds_start: Some(50), // CDS starts 50bp into transcript
            cds_end: Some(400),  // CDS ends 400bp into transcript
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        }
    }

    fn minus_strand_transcript() -> CdotTranscript {
        // Transcript on - strand
        CdotTranscript {
            gene_name: Some("MINUS".to_string()),
            contig: "NC_000001.11".to_string(),
            strand: Strand::Minus,
            exons: vec![
                [3000, 3150, 0, 150],   // Exon 1 (most 3' on genome)
                [2000, 2200, 150, 350], // Exon 2
                [1000, 1100, 350, 450], // Exon 3 (most 5' on genome)
            ],
            cds_start: Some(50),
            cds_end: Some(400),
            exon_cigars: Vec::new(),
            gene_id: None,
            protein: None,
        }
    }

    // CdotTranscript tests
    #[test]
    fn test_transcript_length() {
        let tx = sample_transcript();
        assert_eq!(tx.transcript_length(), 450);
    }

    #[test]
    fn test_cds_length() {
        let tx = sample_transcript();
        assert_eq!(tx.cds_length(), Some(350));
    }

    #[test]
    fn test_exon_for_tx_pos() {
        let tx = sample_transcript();

        // Position in first exon
        let exon = tx.exon_for_tx_pos(50).unwrap();
        assert_eq!(exon.number, 1);

        // Position in second exon
        let exon = tx.exon_for_tx_pos(150).unwrap();
        assert_eq!(exon.number, 2);

        // Position in third exon
        let exon = tx.exon_for_tx_pos(350).unwrap();
        assert_eq!(exon.number, 3);

        // Position beyond transcript
        assert!(tx.exon_for_tx_pos(500).is_none());
    }

    #[test]
    fn test_exon_for_genome_pos() {
        let tx = sample_transcript();

        // Position in first exon
        let exon = tx.exon_for_genome_pos(1050).unwrap();
        assert_eq!(exon.number, 1);

        // Position in second exon
        let exon = tx.exon_for_genome_pos(2100).unwrap();
        assert_eq!(exon.number, 2);

        // Position in intron
        assert!(tx.exon_for_genome_pos(1500).is_none());
    }

    #[test]
    fn test_tx_to_genome_plus_strand() {
        let tx = sample_transcript();

        // First exon
        assert_eq!(tx.tx_to_genome(0), Some(1000));
        assert_eq!(tx.tx_to_genome(50), Some(1050));
        assert_eq!(tx.tx_to_genome(99), Some(1099));

        // Second exon
        assert_eq!(tx.tx_to_genome(100), Some(2000));
        assert_eq!(tx.tx_to_genome(200), Some(2100));

        // Third exon
        assert_eq!(tx.tx_to_genome(300), Some(3000));
    }

    #[test]
    fn test_tx_to_genome_minus_strand() {
        let tx = minus_strand_transcript();

        // First exon (3' on genome)
        assert_eq!(tx.tx_to_genome(0), Some(3149));
        assert_eq!(tx.tx_to_genome(50), Some(3099));
        assert_eq!(tx.tx_to_genome(149), Some(3000));

        // Second exon
        assert_eq!(tx.tx_to_genome(150), Some(2199));
    }

    #[test]
    fn test_genome_to_tx_plus_strand() {
        let tx = sample_transcript();

        // First exon
        assert_eq!(tx.genome_to_tx(1000), Some(0));
        assert_eq!(tx.genome_to_tx(1050), Some(50));

        // Second exon
        assert_eq!(tx.genome_to_tx(2000), Some(100));

        // Intron
        assert!(tx.genome_to_tx(1500).is_none());
    }

    #[test]
    fn test_genome_to_tx_minus_strand() {
        let tx = minus_strand_transcript();

        // First exon (3' on genome)
        assert_eq!(tx.genome_to_tx(3149), Some(0));
        assert_eq!(tx.genome_to_tx(3000), Some(149));

        // Second exon
        assert_eq!(tx.genome_to_tx(2199), Some(150));
    }

    #[test]
    fn test_cds_to_tx() {
        let tx = sample_transcript();

        // Normal CDS position
        assert_eq!(tx.cds_to_tx(1), Some(50)); // c.1 -> tx pos 50
        assert_eq!(tx.cds_to_tx(100), Some(149)); // c.100 -> tx pos 149

        // 5' UTR
        assert_eq!(tx.cds_to_tx(-1), Some(49)); // c.-1 -> tx pos 49
        assert_eq!(tx.cds_to_tx(-50), Some(0)); // c.-50 -> tx pos 0

        // Position 0 invalid
        assert!(tx.cds_to_tx(0).is_none());
    }

    #[test]
    fn test_tx_to_cds() {
        let tx = sample_transcript();

        // 5' UTR
        assert_eq!(tx.tx_to_cds(0), Some(CdsPosition::FivePrimeUtr(50)));
        assert_eq!(tx.tx_to_cds(49), Some(CdsPosition::FivePrimeUtr(1)));

        // CDS
        assert_eq!(tx.tx_to_cds(50), Some(CdsPosition::Cds(1)));
        assert_eq!(tx.tx_to_cds(149), Some(CdsPosition::Cds(100)));
        assert_eq!(tx.tx_to_cds(399), Some(CdsPosition::Cds(350)));

        // 3' UTR
        assert_eq!(tx.tx_to_cds(400), Some(CdsPosition::ThreePrimeUtr(1)));
        assert_eq!(tx.tx_to_cds(449), Some(CdsPosition::ThreePrimeUtr(50)));
    }

    // Exon tests
    #[test]
    fn test_exon_len() {
        let exon = Exon::from_array(1, [1000, 1100, 0, 100]);
        assert_eq!(exon.len(), 100);
        assert!(!exon.is_empty());
    }

    #[test]
    fn test_exon_contains() {
        let exon = Exon::from_array(1, [1000, 1100, 0, 100]);

        assert!(exon.contains_genome_pos(1000));
        assert!(exon.contains_genome_pos(1099));
        assert!(!exon.contains_genome_pos(1100));

        assert!(exon.contains_tx_pos(0));
        assert!(exon.contains_tx_pos(99));
        assert!(!exon.contains_tx_pos(100));
    }

    // CdotMapper tests
    #[test]
    fn test_mapper_new() {
        let mapper = CdotMapper::new();
        assert_eq!(mapper.transcript_count(), 0);
    }

    #[test]
    fn test_mapper_add_transcript() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());

        assert_eq!(mapper.transcript_count(), 1);
        assert!(mapper.get_transcript("NM_000088.3").is_some());
        // Version fallback: NM_000088.4 falls back to NM_000088.3
        assert!(mapper.get_transcript("NM_000088.4").is_some());
        // Completely different accession should return None
        assert!(mapper.get_transcript("NM_999999.1").is_none());
    }

    #[test]
    fn test_mapper_contig_index() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());
        mapper.add_transcript("NM_000088.4".to_string(), sample_transcript());

        let tx_ids = mapper.transcripts_on_contig("NC_000001.11");
        assert_eq!(tx_ids.len(), 2);
        assert!(tx_ids.contains(&"NM_000088.3"));
        assert!(tx_ids.contains(&"NM_000088.4"));

        let tx_ids = mapper.transcripts_on_contig("NC_000002.12");
        assert!(tx_ids.is_empty());
    }

    #[test]
    fn test_contig_alias_lookup_grch38() {
        // Transcripts indexed by RefSeq accession should also be found by UCSC name.
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Lookup by RefSeq accession (canonical key)
        assert_eq!(mapper.transcripts_on_contig("NC_000017.11").len(), 1);
        // Lookup by UCSC alias
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        // Lookup by Ensembl alias
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);
        // Non-existent contig
        assert!(mapper.transcripts_on_contig("chr99").is_empty());
    }

    #[test]
    fn test_contig_alias_lookup_grch37() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "genome_builds": {
                        "GRCh37": {
                            "contig": "NC_000017.10",
                            "strand": "+",
                            "exons": [[48263025, 48263098, 1, 0, 73, "M73"]]
                        }
                    },
                    "start_codon": 10,
                    "stop_codon": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader_with_build(json.as_bytes(), "GRCh37").unwrap();

        assert_eq!(mapper.transcripts_on_contig("NC_000017.10").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("chr17").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("17").len(), 1);

        // Verify the transcript was fully parsed (not dropped due to bad exon format)
        let tx = mapper.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.exons.len(), 1);
        assert_eq!(tx.exons[0][0], 48263025); // genome_start
        assert_eq!(tx.exons[0][1], 48263098); // genome_end
    }

    #[test]
    fn test_contig_alias_transcripts_at_position() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Position within transcript, looked up by UCSC alias
        let results = mapper.transcripts_at_position("chr17", 50184100);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, "NM_000088.3");

        // Position outside transcript
        let results = mapper.transcripts_at_position("chr17", 99999999);
        assert!(results.is_empty());
    }

    #[test]
    fn test_contig_alias_chrm() {
        let json = r#"
        {
            "transcripts": {
                "NM_MITO.1": {
                    "gene_name": "MT_TEST",
                    "contig": "NC_012920.1",
                    "strand": "+",
                    "exons": [[100, 200, 0, 100]],
                    "cds_start": 10,
                    "cds_end": 90
                }
            }
        }
        "#;
        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();

        assert_eq!(mapper.transcripts_on_contig("NC_012920.1").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("chrM").len(), 1);
        assert_eq!(mapper.transcripts_on_contig("MT").len(), 1);
    }

    #[test]
    fn test_mapper_transcripts_at_position() {
        let mut mapper = CdotMapper::new();
        mapper.add_transcript("NM_000088.3".to_string(), sample_transcript());

        // Position within transcript
        let results = mapper.transcripts_at_position("NC_000001.11", 2050);
        assert_eq!(results.len(), 1);

        // Position outside transcript
        let results = mapper.transcripts_at_position("NC_000001.11", 5000);
        assert!(results.is_empty());
    }

    #[test]
    fn test_mapper_from_json() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [
                        [50184096, 50184169, 0, 73],
                        [50185022, 50185148, 73, 199]
                    ],
                    "cds_start": 149,
                    "cds_end": 4544
                }
            }
        }
        "#;

        let mapper = CdotMapper::from_reader(json.as_bytes()).unwrap();
        assert_eq!(mapper.transcript_count(), 1);

        let tx = mapper.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.gene_name.as_deref(), Some("COL1A1"));
        assert_eq!(tx.strand, Strand::Plus);
        assert_eq!(tx.exons.len(), 2);
    }

    // =========================================================================
    // Bincode serialization tests
    // =========================================================================

    #[test]
    fn test_bincode_roundtrip() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [
                        [50184096, 50184169, 0, 73],
                        [50185022, 50185148, 73, 199]
                    ],
                    "cds_start": 149,
                    "cds_end": 4544
                },
                "NM_000059.4": {
                    "gene_name": "BRCA2",
                    "contig": "NC_000013.11",
                    "strand": "+",
                    "exons": [[32315474, 32315667, 0, 193]],
                    "cds_start": 40,
                    "cds_end": 150
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();
        assert_eq!(original.transcript_count(), 2);

        // Roundtrip through bincode file
        let temp_dir = tempfile::TempDir::new().unwrap();
        let bin_path = temp_dir.path().join("roundtrip.bin");
        original.to_bincode_file(&bin_path).unwrap();
        let decoded = CdotMapper::from_bincode_file(&bin_path).unwrap();

        assert_eq!(decoded.transcript_count(), 2);
        let tx = decoded.get_transcript("NM_000088.3").unwrap();
        assert_eq!(tx.gene_name.as_deref(), Some("COL1A1"));
        assert_eq!(tx.contig, "NC_000017.11");
        assert_eq!(tx.strand, Strand::Plus);
        assert_eq!(tx.exons.len(), 2);

        let tx2 = decoded.get_transcript("NM_000059.4").unwrap();
        assert_eq!(tx2.gene_name.as_deref(), Some("BRCA2"));

        // Contig index should be preserved
        assert_eq!(decoded.transcripts_on_contig("NC_000017.11").len(), 1);
        assert_eq!(decoded.transcripts_on_contig("NC_000013.11").len(), 1);

        // Base-to-versioned index should be preserved
        assert!(decoded.get_transcript("NM_000088.4").is_some()); // falls back to .3
    }

    #[test]
    fn test_bincode_file_roundtrip() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        let temp_dir = tempfile::TempDir::new().unwrap();
        let bin_path = temp_dir.path().join("test.bin");

        original.to_bincode_file(&bin_path).unwrap();
        assert!(bin_path.exists());

        let loaded = CdotMapper::from_bincode_file(&bin_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());
    }

    #[test]
    fn test_load_prefers_bincode() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let original = CdotMapper::from_reader(json.as_bytes()).unwrap();

        // Mutate the mapper so bincode content differs from JSON
        let mut from_bin = original.clone();
        from_bin
            .transcripts
            .get_mut("NM_000088.3")
            .unwrap()
            .gene_name = Some("FROM_BIN".to_string());

        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");

        // Write JSON file (gene_name = "COL1A1")
        std::fs::write(&json_path, json).unwrap();

        // Write bincode file (gene_name = "FROM_BIN")
        from_bin.to_bincode_file(&bin_path).unwrap();

        // load() given the JSON path should find and use the .bin sibling
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert_eq!(
            loaded
                .get_transcript("NM_000088.3")
                .unwrap()
                .gene_name
                .as_deref(),
            Some("FROM_BIN"),
            "load() should prefer bincode over JSON"
        );
    }

    #[test]
    fn test_load_falls_back_to_json() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");

        // Write only JSON, no bincode
        std::fs::write(&json_path, json).unwrap();

        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
    }

    #[test]
    fn test_load_falls_back_to_json_on_corrupt_bincode() {
        let json = r#"
        {
            "transcripts": {
                "NM_000088.3": {
                    "gene_name": "COL1A1",
                    "contig": "NC_000017.11",
                    "strand": "+",
                    "exons": [[50184096, 50184169, 0, 73]],
                    "cds_start": 10,
                    "cds_end": 60
                }
            }
        }
        "#;
        let temp_dir = tempfile::TempDir::new().unwrap();
        let json_path = temp_dir.path().join("cdot.json");
        let bin_path = temp_dir.path().join("cdot.bin");

        // Write valid JSON and corrupt bincode
        std::fs::write(&json_path, json).unwrap();
        std::fs::write(&bin_path, b"not valid bincode data").unwrap();

        // load() should fall back to JSON despite corrupt .bin
        let loaded = CdotMapper::load(&json_path).unwrap();
        assert_eq!(loaded.transcript_count(), 1);
        assert!(loaded.get_transcript("NM_000088.3").is_some());
    }

    // =========================================================================
    // CIGAR parsing tests
    // =========================================================================

    #[test]
    fn test_parse_cigar_simple_match() {
        let ops = parse_cigar("M185").unwrap();
        assert_eq!(ops, vec![CigarOp::Match(185)]);
    }

    #[test]
    fn test_parse_cigar_with_insertion() {
        let ops = parse_cigar("M185 I3 M250").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(185),
                CigarOp::Insertion(3),
                CigarOp::Match(250),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_with_deletion() {
        let ops = parse_cigar("M504 D2 M123").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(504),
                CigarOp::Deletion(2),
                CigarOp::Match(123),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_complex() {
        let ops = parse_cigar("M6 D1 M4 I2 M3").unwrap();
        assert_eq!(
            ops,
            vec![
                CigarOp::Match(6),
                CigarOp::Deletion(1),
                CigarOp::Match(4),
                CigarOp::Insertion(2),
                CigarOp::Match(3),
            ]
        );
    }

    #[test]
    fn test_parse_cigar_empty() {
        let ops = parse_cigar("").unwrap();
        assert!(ops.is_empty());
    }

    #[test]
    fn test_parse_cigar_whitespace_only() {
        let ops = parse_cigar("   ").unwrap();
        assert!(ops.is_empty());
    }

    #[test]
    fn test_parse_cigar_invalid_operation() {
        let result = parse_cigar("X5");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_cigar_invalid_length() {
        let result = parse_cigar("Mabc");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_cigar_too_short_token() {
        let result = parse_cigar("M");
        assert!(result.is_err());
    }

    #[test]
    fn test_cumulative_insertion_offset_before_insertion() {
        // CIGAR: M185 I3 M250 — 3bp insertion at tx position 186-188
        // At tx position 100 (before insertion): offset = 0
        let cigar = vec![
            CigarOp::Match(185),
            CigarOp::Insertion(3),
            CigarOp::Match(250),
        ];
        assert_eq!(cumulative_insertion_offset(&cigar, 100), 0);
    }

    #[test]
    fn test_cumulative_insertion_offset_after_insertion() {
        // At tx position 200 (after insertion): offset = 3
        let cigar = vec![
            CigarOp::Match(185),
            CigarOp::Insertion(3),
            CigarOp::Match(250),
        ];
        assert_eq!(cumulative_insertion_offset(&cigar, 200), 3);
    }

    #[test]
    fn test_cumulative_insertion_offset_at_end() {
        // At tx position 437 (end of exon, 185+3+250-1): offset = 3
        let cigar = vec![
            CigarOp::Match(185),
            CigarOp::Insertion(3),
            CigarOp::Match(250),
        ];
        assert_eq!(cumulative_insertion_offset(&cigar, 437), 3);
    }

    #[test]
    fn test_cumulative_insertion_offset_no_insertions() {
        let cigar = vec![CigarOp::Match(500)];
        assert_eq!(cumulative_insertion_offset(&cigar, 250), 0);
    }

    #[test]
    fn test_cumulative_insertion_offset_multiple_insertions() {
        // M100 I2 M100 I5 M100 — two insertions
        let cigar = vec![
            CigarOp::Match(100),
            CigarOp::Insertion(2),
            CigarOp::Match(100),
            CigarOp::Insertion(5),
            CigarOp::Match(100),
        ];
        // Before first insertion
        assert_eq!(cumulative_insertion_offset(&cigar, 50), 0);
        // After first insertion, before second
        assert_eq!(cumulative_insertion_offset(&cigar, 150), 2);
        // After both insertions
        assert_eq!(cumulative_insertion_offset(&cigar, 300), 7);
    }

    #[test]
    fn test_cumulative_insertion_offset_with_deletion() {
        // M100 D5 M100 I3 M100 — deletion doesn't affect insertion offset
        let cigar = vec![
            CigarOp::Match(100),
            CigarOp::Deletion(5),
            CigarOp::Match(100),
            CigarOp::Insertion(3),
            CigarOp::Match(100),
        ];
        // Before insertion (deletions don't advance tx position)
        assert_eq!(cumulative_insertion_offset(&cigar, 150), 0);
        // After insertion
        assert_eq!(cumulative_insertion_offset(&cigar, 250), 3);
    }
}