ferro-hgvs 1.0.0

HGVS variant normalizer - part of the ferro bioinformatics toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Position types for different coordinate systems
//!
//! HGVS supports multiple coordinate systems:
//! - Genomic (g.): 1-based positions on a chromosome/contig
//! - Coding (c.): Positions relative to CDS start, with intron offsets
//! - Transcript (n.): Positions on non-coding transcript
//! - RNA (r.): Positions on RNA
//! - Protein (p.): Amino acid positions

use serde::{Deserialize, Serialize};
use std::fmt;

/// Special genome position markers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SpecialPosition {
    /// p-arm telomere (short arm end)
    Pter,
    /// q-arm telomere (long arm end)
    Qter,
    /// Centromere
    Cen,
}

impl fmt::Display for SpecialPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpecialPosition::Pter => write!(f, "pter"),
            SpecialPosition::Qter => write!(f, "qter"),
            SpecialPosition::Cen => write!(f, "cen"),
        }
    }
}

/// Genomic position (g. coordinates)
///
/// Simple 1-based position on a genomic reference sequence.
/// Can also represent special positions like pter, qter, or cen.
/// Supports offsets for uncertain position notation (e.g., g.12345-? or g.67890+?),
/// using the same syntax as intronic offsets but applied to genomic coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GenomePos {
    /// 1-based position (0 if special position is set)
    pub base: u64,
    /// Special position marker (pter, qter, cen)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub special: Option<SpecialPosition>,
    /// Optional offset from the base position (e.g., -? for uncertain upstream, +? for uncertain downstream)
    ///
    /// The uncertain forms are stored in band, as
    /// [`OFFSET_UNKNOWN_POSITIVE`] (`+?`) and [`OFFSET_UNKNOWN_NEGATIVE`]
    /// (`-?`). Name the constants rather than their current values: they are
    /// defined in exactly one place, and a doc that respells them as literals
    /// is a second declaration in prose.
    ///
    /// [`OFFSET_UNKNOWN_POSITIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_POSITIVE
    /// [`OFFSET_UNKNOWN_NEGATIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_NEGATIVE
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<i64>,
}

impl GenomePos {
    pub fn new(base: u64) -> Self {
        Self {
            base,
            special: None,
            offset: None,
        }
    }

    pub fn with_offset(base: u64, offset: i64) -> Self {
        Self {
            base,
            special: None,
            offset: Some(offset),
        }
    }

    /// Create a pter (p-arm telomere) position
    pub fn pter() -> Self {
        Self {
            base: 0,
            special: Some(SpecialPosition::Pter),
            offset: None,
        }
    }

    /// Create a qter (q-arm telomere) position
    pub fn qter() -> Self {
        Self {
            base: 0,
            special: Some(SpecialPosition::Qter),
            offset: None,
        }
    }

    /// Create a cen (centromere) position
    pub fn cen() -> Self {
        Self {
            base: 0,
            special: Some(SpecialPosition::Cen),
            offset: None,
        }
    }

    /// Check if this is a special position (pter, qter, cen)
    pub fn is_special(&self) -> bool {
        self.special.is_some()
    }
}

/// The unknown-offset sentinels, under their historical genome-axis names.
///
/// These are **re-exports**, not a second definition. The pair is defined once,
/// by the parser that produces it
/// ([`crate::hgvs::parser::position::OFFSET_UNKNOWN_POSITIVE`] and its negative
/// twin), because the values enter the AST there and every axis — `g.`, `c.`,
/// `n.`, `r.` — stores the same two.
///
/// They were previously declared here as their own `pub const`s, spelled as
/// bare `i64::MAX` / `i64::MIN` literals. That is the same failure mode
/// `unknown_offset_marker` was extracted to remove, one level up: two
/// independent definitions of one value pair, where changing either leaves the
/// other silently behind and the rendering stops matching the parser. Kept as
/// aliases rather than deleted because they are public API of a published
/// crate.
pub use crate::hgvs::parser::position::{
    OFFSET_UNKNOWN_NEGATIVE as GENOME_OFFSET_UNKNOWN_NEGATIVE,
    OFFSET_UNKNOWN_POSITIVE as GENOME_OFFSET_UNKNOWN_POSITIVE,
};

/// The rendered form of an unknown-offset sentinel (`+?` / `-?`), or `None`
/// when `offset` is a measured intronic distance.
///
/// The sentinels are stored **in band** (`i64::MAX` / `i64::MIN`, see
/// [`crate::hgvs::parser::position::OFFSET_UNKNOWN_POSITIVE`]), so every
/// `Display` that prints an offset has to ask this question first or the raw
/// 19-digit integer escapes into a description as if it were a real distance.
///
/// It exists as one function, keyed off the named constants, because the
/// alternative had already failed: `GenomePos::Display` compared against
/// `GENOME_OFFSET_UNKNOWN_*`, `CdsPos::Display` re-spelled the same pair as
/// bare `i64::MAX` / `i64::MIN` literals, and `TxPos`/`RnaPos` — added later —
/// had no arm at all, so a parsed `n.5+?` printed as `5+9223372036854775807`.
/// Three spellings of one pair is how the fourth axis came to have none.
fn unknown_offset_marker(offset: i64) -> Option<&'static str> {
    use crate::hgvs::parser::position::{OFFSET_UNKNOWN_NEGATIVE, OFFSET_UNKNOWN_POSITIVE};
    match offset {
        OFFSET_UNKNOWN_POSITIVE => Some("+?"),
        OFFSET_UNKNOWN_NEGATIVE => Some("-?"),
        _ => None,
    }
}

impl fmt::Display for GenomePos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(special) = &self.special {
            write!(f, "{}", special)
        } else {
            write!(f, "{}", self.base)?;
            if let Some(offset) = self.offset {
                // NOTE: unlike the transcript-relative axes below, a zero offset
                // renders as nothing here rather than as `+0`. Unchanged.
                if let Some(marker) = unknown_offset_marker(offset) {
                    write!(f, "{}", marker)?;
                } else if offset > 0 {
                    write!(f, "+{}", offset)?;
                } else if offset < 0 {
                    write!(f, "{}", offset)?;
                }
            }
            Ok(())
        }
    }
}

/// CDS position (c. coordinates)
///
/// Position relative to the start of the coding sequence.
/// Can include intronic offsets (e.g., c.100+5 or c.100-10).
/// Negative positions are upstream of CDS start.
/// Positions with * prefix are downstream of stop codon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CdsPos {
    /// Base position in CDS, **1-based** (`c.1` is the A of the start codon).
    ///
    /// Negative for 5' UTR, counting back from `c.1` with no zero in between, so
    /// `c.-1` is the base immediately before the start codon. With `utr3`, counts
    /// forward from the stop codon (`c.*1`). The value `0` is not a position: it is
    /// [`CDS_BASE_UNKNOWN`], the sentinel for `c.?`, and also the placeholder `base`
    /// carried by a `special` position.
    pub base: i64,
    /// Intronic offset (+ for downstream, - for upstream of exon)
    pub offset: Option<i64>,
    /// Whether this is a 3' UTR position (uses * notation)
    pub utr3: bool,
    /// Special position marker (pter/qter/cen). When `Some`, `base` is a 0
    /// sentinel and `offset` is `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub special: Option<SpecialPosition>,
}

/// Sentinel value for unknown CDS base position (?)
pub const CDS_BASE_UNKNOWN: i64 = 0;

impl CdsPos {
    /// Create a simple exonic CDS position
    pub fn new(base: i64) -> Self {
        Self {
            base,
            offset: None,
            utr3: false,
            special: None,
        }
    }

    /// Create an unknown position (represented as ? in HGVS)
    /// Optionally with an offset (e.g., ?-232)
    pub fn unknown(offset: Option<i64>) -> Self {
        Self {
            base: CDS_BASE_UNKNOWN,
            offset,
            utr3: false,
            special: None,
        }
    }

    /// Check if this is an unknown position (?)
    ///
    /// Note this inspects the *base* only: `c.100-?` has a known base and an
    /// unknown offset, so it is not "unknown" by this predicate. Use
    /// [`has_unknown_offset`](Self::has_unknown_offset) for that.
    pub fn is_unknown(&self) -> bool {
        self.base == CDS_BASE_UNKNOWN && !self.utr3 && self.special.is_none()
    }

    /// Whether the offset is one of the parser's unknown-offset sentinels
    /// (`+?` → [`OFFSET_UNKNOWN_POSITIVE`], `-?` → [`OFFSET_UNKNOWN_NEGATIVE`])
    /// rather than a measured intronic distance.
    ///
    /// Callers doing coordinate arithmetic MUST check this first: the
    /// sentinels are `i64::MAX` / `i64::MIN`, so using one as a distance
    /// overflows (issue #1087). Per the spec these denote an unknown position
    /// 3'/5' of the base, unbounded in that direction, so no coordinate can be
    /// derived from them at all.
    ///
    /// [`OFFSET_UNKNOWN_POSITIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_POSITIVE
    /// [`OFFSET_UNKNOWN_NEGATIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_NEGATIVE
    pub fn has_unknown_offset(&self) -> bool {
        self.offset
            .is_some_and(crate::hgvs::parser::position::is_unknown_offset)
    }

    /// Create a CDS position with intronic offset
    pub fn with_offset(base: i64, offset: i64) -> Self {
        Self {
            base,
            offset: Some(offset),
            utr3: false,
            special: None,
        }
    }

    /// Create a 3' UTR position
    pub fn utr3(base: i64) -> Self {
        Self {
            base,
            offset: None,
            utr3: true,
            special: None,
        }
    }

    /// Create a pter (telomere, first transcript nucleotide) position.
    pub fn pter() -> Self {
        Self {
            base: 0,
            offset: None,
            utr3: false,
            special: Some(SpecialPosition::Pter),
        }
    }

    /// Create a qter (telomere, last transcript nucleotide) position.
    pub fn qter() -> Self {
        Self {
            base: 0,
            offset: None,
            utr3: false,
            special: Some(SpecialPosition::Qter),
        }
    }

    /// Create a cen (centromere — unresolvable on a transcript) position.
    pub fn cen() -> Self {
        Self {
            base: 0,
            offset: None,
            utr3: false,
            special: Some(SpecialPosition::Cen),
        }
    }

    /// Whether this is a special telomere/centromere marker.
    pub fn is_special(&self) -> bool {
        self.special.is_some()
    }

    /// Check if this position is intronic
    pub fn is_intronic(&self) -> bool {
        self.offset.is_some() && self.offset != Some(0)
    }

    /// Check if this position is in 5' UTR
    pub fn is_5utr(&self) -> bool {
        self.special.is_none() && !self.utr3 && self.base < 1 && self.offset.is_none()
    }

    /// Check if this position is in 3' UTR
    pub fn is_3utr(&self) -> bool {
        self.utr3
    }
}

impl fmt::Display for CdsPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(special) = self.special {
            return write!(f, "{special}");
        }
        if self.utr3 {
            write!(f, "*{}", self.base)?;
        } else if self.base == CDS_BASE_UNKNOWN {
            // Unknown position
            write!(f, "?")?;
        } else {
            write!(f, "{}", self.base)?;
        }
        if let Some(offset) = self.offset {
            if let Some(marker) = unknown_offset_marker(offset) {
                write!(f, "{}", marker)?;
            } else if offset >= 0 {
                write!(f, "+{}", offset)?;
            } else {
                write!(f, "{}", offset)?;
            }
        }
        Ok(())
    }
}

/// Transcript position (n. coordinates)
///
/// Position on a non-coding transcript. Negative positions represent
/// positions upstream of the transcript start (e.g., n.-30 is 30 bases
/// before the transcript start). Downstream positions use * notation
/// (e.g., n.*5 is 5 bases after the transcript end).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TxPos {
    /// Position on transcript, **1-based** (`n.1` is the first transcribed base).
    ///
    /// Negative for positions upstream of the transcript start, counting back from
    /// `n.1` with no zero in between, so `n.-1` is the base immediately before it.
    /// With `downstream`, counts forward from the transcript end (`n.*1`).
    pub base: i64,
    /// Intronic offset
    pub offset: Option<i64>,
    /// Whether this is a downstream position (uses * notation)
    pub downstream: bool,
}

impl TxPos {
    pub fn new(base: i64) -> Self {
        Self {
            base,
            offset: None,
            downstream: false,
        }
    }

    pub fn with_offset(base: i64, offset: i64) -> Self {
        Self {
            base,
            offset: Some(offset),
            downstream: false,
        }
    }

    /// Create a downstream position (n.*5 notation)
    pub fn downstream(base: i64) -> Self {
        Self {
            base,
            offset: None,
            downstream: true,
        }
    }

    /// Create a downstream position with offset (n.*5+10 notation)
    pub fn downstream_with_offset(base: i64, offset: i64) -> Self {
        Self {
            base,
            offset: Some(offset),
            downstream: true,
        }
    }

    pub fn is_intronic(&self) -> bool {
        self.offset.is_some() && self.offset != Some(0)
    }

    /// Whether the offset is one of the parser's unknown-offset sentinels
    /// (`+?` → [`OFFSET_UNKNOWN_POSITIVE`], `-?` → [`OFFSET_UNKNOWN_NEGATIVE`])
    /// rather than a measured intronic distance.
    ///
    /// The n.-axis sibling of [`CdsPos::has_unknown_offset`], with the same
    /// contract: the sentinels are `i64::MAX` / `i64::MIN`, so using one as a
    /// distance overflows, and per the spec they denote an unknown position
    /// unbounded in one direction, from which no distance can be derived at
    /// all. Callers that classify or measure an offset MUST check this first
    /// (issues #1087, #1767).
    ///
    /// [`OFFSET_UNKNOWN_POSITIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_POSITIVE
    /// [`OFFSET_UNKNOWN_NEGATIVE`]: crate::hgvs::parser::position::OFFSET_UNKNOWN_NEGATIVE
    pub fn has_unknown_offset(&self) -> bool {
        self.offset
            .is_some_and(crate::hgvs::parser::position::is_unknown_offset)
    }

    /// Check if this is an upstream position (negative base)
    pub fn is_upstream(&self) -> bool {
        self.base < 0 && !self.downstream
    }

    /// Check if this is a downstream position (uses * notation)
    pub fn is_downstream(&self) -> bool {
        self.downstream
    }
}

impl fmt::Display for TxPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.downstream {
            write!(f, "*{}", self.base)?;
        } else {
            write!(f, "{}", self.base)?;
        }
        if let Some(offset) = self.offset {
            if let Some(marker) = unknown_offset_marker(offset) {
                write!(f, "{}", marker)?;
            } else if offset >= 0 {
                write!(f, "+{}", offset)?;
            } else {
                write!(f, "{}", offset)?;
            }
        }
        Ok(())
    }
}

/// RNA position (r. coordinates)
///
/// Position on an RNA sequence (lowercase nucleotides).
/// Similar to CdsPos, supports 5' UTR (negative base) and 3' UTR (*base) positions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RnaPos {
    /// Position relative to start codon (can be negative for 5' UTR)
    pub base: i64,
    /// Intronic offset
    pub offset: Option<i64>,
    /// True if position is in 3' UTR (uses *N notation)
    pub utr3: bool,
}

impl RnaPos {
    /// Create a simple RNA position
    pub fn new(base: i64) -> Self {
        Self {
            base,
            offset: None,
            utr3: false,
        }
    }

    /// Create an RNA position with intronic offset
    pub fn with_offset(base: i64, offset: i64) -> Self {
        Self {
            base,
            offset: Some(offset),
            utr3: false,
        }
    }

    /// Create a 3' UTR position
    pub fn utr3(base: i64) -> Self {
        Self {
            base,
            offset: None,
            utr3: true,
        }
    }

    /// Check if this position is intronic
    pub fn is_intronic(&self) -> bool {
        self.offset.is_some() && self.offset != Some(0)
    }

    /// Check if this position is in 5' UTR
    pub fn is_5utr(&self) -> bool {
        !self.utr3 && self.base < 1 && self.offset.is_none()
    }

    /// Check if this position is in 3' UTR
    pub fn is_3utr(&self) -> bool {
        self.utr3
    }
}

impl fmt::Display for RnaPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.utr3 {
            write!(f, "*{}", self.base)?;
        } else {
            write!(f, "{}", self.base)?;
        }
        if let Some(offset) = self.offset {
            if let Some(marker) = unknown_offset_marker(offset) {
                write!(f, "{}", marker)?;
            } else if offset >= 0 {
                write!(f, "+{}", offset)?;
            } else {
                write!(f, "{}", offset)?;
            }
        }
        Ok(())
    }
}

/// Amino acid enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AminoAcid {
    Ala, // A
    Arg, // R
    Asn, // N
    Asp, // D
    Cys, // C
    Gln, // Q
    Glu, // E
    Gly, // G
    His, // H
    Ile, // I
    Leu, // L
    Lys, // K
    Met, // M
    Phe, // F
    Pro, // P
    Pyl, // O (pyrrolysine)
    Sec, // U (selenocysteine)
    Ser, // S
    Thr, // T
    Trp, // W
    Tyr, // Y
    Val, // V
    Ter, // * (stop codon)
    Xaa, // X (unknown)
}

/// How protein (`p.`) names spell the translation stop codon and amino acids.
///
/// HGVS sanctions both `Ter`/`*` for the stop and three-/one-letter amino-acid
/// codes; this selects which conformant style to emit. `Default` is the
/// spec-preferred `Ter` + three-letter form, so default rendering is unchanged.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ProteinRenderStyle {
    /// Stop-codon spelling (only distinguishable in three-letter mode).
    pub stop: TerStyle,
    /// Amino-acid code width.
    pub aa_code: AaCode,
}

/// Stop-codon spelling: `Ter` (three-letter only) or `*` (both widths).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TerStyle {
    /// `Ter` — spec-preferred, three-letter only.
    #[default]
    Ter,
    /// `*` — valid in one- and three-letter descriptions.
    Star,
}

/// Amino-acid code width: three-letter (`Ser`) or one-letter (`S`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AaCode {
    /// Three-letter codes (`Ser`, `Leu`, …).
    #[default]
    Three,
    /// One-letter codes (`S`, `L`, …).
    One,
}

impl ProteinRenderStyle {
    /// The spelling for the translation stop codon under this style.
    ///
    /// `Ter` is a three-letter-only token per the HGVS spec ("`Ter`
    /// (three-letter code)… `*` (three- and one-letter code)"). There is no
    /// one-letter `Ter`, so one-letter mode always yields `*`; three-letter
    /// mode honors the `stop` toggle.
    pub fn ter_token(&self) -> &'static str {
        if self.aa_code == AaCode::One || self.stop == TerStyle::Star {
            "*"
        } else {
            "Ter"
        }
    }
}

impl AminoAcid {
    /// Parse from 3-letter code
    pub fn from_three_letter(s: &str) -> Option<Self> {
        match s {
            "Ala" => Some(Self::Ala),
            "Arg" => Some(Self::Arg),
            "Asn" => Some(Self::Asn),
            "Asp" => Some(Self::Asp),
            "Cys" => Some(Self::Cys),
            "Gln" => Some(Self::Gln),
            "Glu" => Some(Self::Glu),
            "Gly" => Some(Self::Gly),
            "His" => Some(Self::His),
            "Ile" => Some(Self::Ile),
            "Leu" => Some(Self::Leu),
            "Lys" => Some(Self::Lys),
            "Met" => Some(Self::Met),
            "Phe" => Some(Self::Phe),
            "Pro" => Some(Self::Pro),
            "Pyl" => Some(Self::Pyl),
            "Sec" => Some(Self::Sec),
            "Ser" => Some(Self::Ser),
            "Thr" => Some(Self::Thr),
            "Trp" => Some(Self::Trp),
            "Tyr" => Some(Self::Tyr),
            "Val" => Some(Self::Val),
            "Ter" => Some(Self::Ter),
            "Xaa" => Some(Self::Xaa),
            _ => None,
        }
    }

    /// Get 3-letter code
    pub fn to_three_letter(&self) -> &'static str {
        match self {
            Self::Ala => "Ala",
            Self::Arg => "Arg",
            Self::Asn => "Asn",
            Self::Asp => "Asp",
            Self::Cys => "Cys",
            Self::Gln => "Gln",
            Self::Glu => "Glu",
            Self::Gly => "Gly",
            Self::His => "His",
            Self::Ile => "Ile",
            Self::Leu => "Leu",
            Self::Lys => "Lys",
            Self::Met => "Met",
            Self::Phe => "Phe",
            Self::Pro => "Pro",
            Self::Pyl => "Pyl",
            Self::Sec => "Sec",
            Self::Ser => "Ser",
            Self::Thr => "Thr",
            Self::Trp => "Trp",
            Self::Tyr => "Tyr",
            Self::Val => "Val",
            Self::Ter => "Ter",
            Self::Xaa => "Xaa",
        }
    }

    /// Get 1-letter code
    pub fn to_one_letter(&self) -> char {
        match self {
            Self::Ala => 'A',
            Self::Arg => 'R',
            Self::Asn => 'N',
            Self::Asp => 'D',
            Self::Cys => 'C',
            Self::Gln => 'Q',
            Self::Glu => 'E',
            Self::Gly => 'G',
            Self::His => 'H',
            Self::Ile => 'I',
            Self::Leu => 'L',
            Self::Lys => 'K',
            Self::Met => 'M',
            Self::Phe => 'F',
            Self::Pro => 'P',
            Self::Pyl => 'O',
            Self::Sec => 'U',
            Self::Ser => 'S',
            Self::Thr => 'T',
            Self::Trp => 'W',
            Self::Tyr => 'Y',
            Self::Val => 'V',
            Self::Ter => '*',
            Self::Xaa => 'X',
        }
    }

    /// Render this amino acid under `style` (used by all protein `p.`
    /// rendering). The stop codon follows [`ProteinRenderStyle::ter_token`].
    pub fn fmt_styled(&self, f: &mut fmt::Formatter<'_>, style: ProteinRenderStyle) -> fmt::Result {
        match self {
            Self::Ter => write!(f, "{}", style.ter_token()),
            _ if style.aa_code == AaCode::One => write!(f, "{}", self.to_one_letter()),
            _ => write!(f, "{}", self.to_three_letter()),
        }
    }

    /// Parse from 1-letter code (uppercase only)
    ///
    /// HGVS notation uses uppercase for 1-letter amino acid codes.
    /// Lowercase letters are reserved for other notations like "fs" (frameshift)
    /// and "ext" (extension).
    ///
    /// # Examples
    ///
    /// ```
    /// use ferro_hgvs::hgvs::location::AminoAcid;
    ///
    /// assert_eq!(AminoAcid::from_one_letter('V'), Some(AminoAcid::Val));
    /// assert_eq!(AminoAcid::from_one_letter('v'), None); // lowercase not accepted
    /// assert_eq!(AminoAcid::from_one_letter('*'), Some(AminoAcid::Ter));
    /// ```
    pub fn from_one_letter(c: char) -> Option<Self> {
        match c {
            'A' => Some(Self::Ala),
            'R' => Some(Self::Arg),
            'N' => Some(Self::Asn),
            'D' => Some(Self::Asp),
            'C' => Some(Self::Cys),
            'Q' => Some(Self::Gln),
            'E' => Some(Self::Glu),
            'G' => Some(Self::Gly),
            'H' => Some(Self::His),
            'I' => Some(Self::Ile),
            'L' => Some(Self::Leu),
            'K' => Some(Self::Lys),
            'M' => Some(Self::Met),
            'F' => Some(Self::Phe),
            'O' => Some(Self::Pyl),
            'P' => Some(Self::Pro),
            'U' => Some(Self::Sec),
            'S' => Some(Self::Ser),
            'T' => Some(Self::Thr),
            'W' => Some(Self::Trp),
            'Y' => Some(Self::Tyr),
            'V' => Some(Self::Val),
            '*' => Some(Self::Ter),
            'X' => Some(Self::Xaa),
            _ => None,
        }
    }
}

impl fmt::Display for AminoAcid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_styled(f, ProteinRenderStyle::default())
    }
}

/// Protein position (p. coordinates)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProtPos {
    /// Amino acid at this position
    pub aa: AminoAcid,
    /// 1-based position in protein
    pub number: u64,
}

impl ProtPos {
    pub fn new(aa: AminoAcid, number: u64) -> Self {
        Self { aa, number }
    }

    /// Render this position under `style`, delegating the amino-acid spelling
    /// (including a position-side stop) to [`AminoAcid::fmt_styled`].
    pub fn fmt_styled(&self, f: &mut fmt::Formatter<'_>, style: ProteinRenderStyle) -> fmt::Result {
        self.aa.fmt_styled(f, style)?;
        write!(f, "{}", self.number)
    }
}

impl fmt::Display for ProtPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_styled(f, ProteinRenderStyle::default())
    }
}

/// A [`ProtPos`] paired with a render style so it can be dropped into the
/// generic `Interval<T>` / `Mu<T>` `Display` machinery without duplicating that
/// structural logic. `PartialEq` compares the position AND the style; within one
/// render both interval endpoints carry the same style, so the interval's
/// point-collapse (`start == end`) still reduces to position equality.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct StyledProtPos(pub ProtPos, pub ProteinRenderStyle);

impl fmt::Display for StyledProtPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt_styled(f, self.1)
    }
}

/// IVS (Intervening Sequence) position notation
///
/// Older notation for intronic positions that's still commonly used in
/// clinical settings. e.g., IVS1+5 means position +5 in intron 1.
/// This is equivalent to c.N+5 where N is the last base of the upstream exon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct IvsPos {
    /// Intron number (1-based)
    pub intron: u32,
    /// Offset from the boundary (positive for 5' end, negative for 3' end)
    pub offset: i64,
}

impl IvsPos {
    /// Create a new IVS position
    pub fn new(intron: u32, offset: i64) -> Self {
        Self { intron, offset }
    }

    /// Check if this is a 5' boundary position (positive offset)
    pub fn is_5prime(&self) -> bool {
        self.offset > 0
    }

    /// Check if this is a 3' boundary position (negative offset)
    pub fn is_3prime(&self) -> bool {
        self.offset < 0
    }

    /// Convert to CDS position if the transcript boundary is known
    ///
    /// Requires the transcript position of the exon boundary.
    pub fn to_cds_pos(&self, boundary_cds_pos: i64, is_utr3: bool) -> CdsPos {
        CdsPos {
            base: boundary_cds_pos,
            offset: Some(self.offset),
            utr3: is_utr3,
            special: None,
        }
    }

    // --- Splice-distance convenience predicates ---------------------------
    //
    // These two restate rungs that ferro defines once, on
    // `reference::transcript::SpliceSiteType::from_distance_on_side` (donor
    // 2/6/20/50, acceptor 2/12/20/50). They are NOT derived from it, and that
    // is deliberate rather than an oversight (#1766):
    //
    // `hgvs::location` is a leaf module of parsed-notation types with no
    // production dependency on the `reference` layer — `use crate::reference::`
    // appears under `src/hgvs/` exactly once, inside a test — and `IvsPos` is a
    // notation this crate *parses*, not something a reference resolves. Adding
    // an inward edge from the notation layer onto the reference layer to spell
    // two one-line predicates would invert that for no gain in behaviour.
    //
    // The *drift* risk that deriving would remove is covered instead by a
    // cross-test: `the_ivs_pos_predicates_agree_with_the_one_shape_a_ladder` in
    // `tests/it/splice_ladder_shapes.rs` fails if either literal below and the
    // ladder's corresponding rung ever stop agreeing over `-300..=300`.
    //
    // **Drift is not the whole of it, and this note used to claim it was.**
    // Deriving buys a second thing these two do not get: the ladder takes its
    // magnitude with `unsigned_abs`, while both predicates below still use
    // `abs()`. That is the difference `IntronPosition`'s sibling note calls the
    // practical point of deriving, and it is real here — `-?` parses to
    // `offset == i64::MIN` (`parser::position::OFFSET_UNKNOWN_NEGATIVE`), and
    // `i64::MIN.abs()` panics under `debug_assertions` and wraps back to a
    // negative in release, where it reads as a *canonical splice site*. The
    // cross-test's `-300..=300` sweep cannot see that, by construction: the
    // sentinels are the only offsets at which the two spellings differ, and
    // they are outside its range.
    //
    // So the guarantee here is narrower than deriving's, in exactly one place.
    // That place is **#1826 item 1**, which tracks it; #1742 applied the same
    // two-word fix to `IntronPosition` and deliberately stopped short of this
    // file. Do not widen the cross-test's range without fixing these two first
    // — it will panic rather than fail, which reads as a broken test.

    /// Check if this is a deep intronic position (>50bp from exon)
    ///
    /// `unsigned_abs` rather than `abs`: [`IvsNotation::to_ivs`] maps a `CdsPos` /
    /// `TxPos` offset straight in, so an unknown offset (`c.100-?`) reaches
    /// this predicate, and `i64::MIN.abs()` overflows (#1767). This reads a
    /// *measured* distance, so screen sentinels before asking. `IvsPos` carries
    /// a bare `i64`, so the applicable screen is the scalar
    /// [`is_unknown_offset`], not [`CdsPos::has_unknown_offset`] /
    /// [`TxPos::has_unknown_offset`], which a caller holding only an `IvsPos`
    /// no longer has.
    ///
    /// **This is deliberately unlike [`IntronicRegion::from_offset`], which
    /// since #1841 declines a sentinel rather than asking the caller to screen.**
    /// The two are not the same shape and the difference is not an oversight: a
    /// `bool` predicate has no way to say "no answer", so pushing the rule in
    /// here would only move the fabricated answer from `DeepIntronic` to
    /// `false`. Making these decline needs its own decision about what the four
    /// `IvsPos`/`IntronPosition` predicates return.
    ///
    /// The 50 mirrors `SpliceSiteType::DeepIntronic`; see the note above for
    /// why this restates the rung rather than deriving it, and which test keeps
    /// the two from drifting apart.
    ///
    /// [`IntronicRegion::from_offset`]: crate::convert::noncoding::IntronicRegion::from_offset
    /// [`is_unknown_offset`]: crate::hgvs::parser::position::is_unknown_offset
    pub fn is_deep_intronic(&self) -> bool {
        self.offset.unsigned_abs() > 50
    }

    /// Check if this is at a canonical splice site (within 2bp of exon)
    ///
    /// The 2 mirrors `SpliceSiteType::DonorCanonical`/`AcceptorCanonical`,
    /// which share that rung, so reading the side off the sign of `offset`
    /// cannot change the verdict. See the note above.
    ///
    /// See [`IvsPos::is_deep_intronic`] for why this is `unsigned_abs`.
    pub fn is_canonical_splice_site(&self) -> bool {
        self.offset.unsigned_abs() <= 2
    }
}

impl fmt::Display for IvsPos {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The fifth `Display` that has to ask this question, and the one the
        // `GenomePos`/`CdsPos`/`TxPos`/`RnaPos` sweep missed. `IvsNotation::to_ivs`
        // maps a `CdsPos`/`TxPos` offset straight in, so a parsed `c.100+?`
        // reaches here and rendered as `IVS3+9223372036854775807`.
        //
        // The sign is taken from the marker rather than from the number, which
        // is why this cannot be written as a prefix to the arms below: the
        // negative sentinel is `i64::MIN`, whose `Display` already carries a
        // `-`, while the positive one needs a `+` this arm would have to add.
        if let Some(marker) = unknown_offset_marker(self.offset) {
            write!(f, "IVS{}{}", self.intron, marker)
        } else if self.offset >= 0 {
            write!(f, "IVS{}+{}", self.intron, self.offset)
        } else {
            write!(f, "IVS{}{}", self.intron, self.offset)
        }
    }
}

/// Extension trait for CdsPos to convert to/from IVS notation
pub trait IvsNotation {
    /// Convert to IVS notation if this is an intronic position
    fn to_ivs(&self, intron_number: u32) -> Option<IvsPos>;

    /// Check if this position can be represented in IVS notation
    fn has_ivs_notation(&self) -> bool;
}

impl IvsNotation for CdsPos {
    fn to_ivs(&self, intron_number: u32) -> Option<IvsPos> {
        self.offset.map(|offset| IvsPos::new(intron_number, offset))
    }

    fn has_ivs_notation(&self) -> bool {
        self.is_intronic()
    }
}

impl IvsNotation for TxPos {
    fn to_ivs(&self, intron_number: u32) -> Option<IvsPos> {
        self.offset.map(|offset| IvsPos::new(intron_number, offset))
    }

    fn has_ivs_notation(&self) -> bool {
        self.is_intronic()
    }
}

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

    #[test]
    fn test_genome_pos_display() {
        let pos = GenomePos::new(12345);
        assert_eq!(format!("{}", pos), "12345");
    }

    #[test]
    fn test_cds_pos_simple() {
        let pos = CdsPos::new(100);
        assert_eq!(format!("{}", pos), "100");
        assert!(!pos.is_intronic());
    }

    #[test]
    fn test_cds_pos_with_offset() {
        let pos = CdsPos::with_offset(100, 5);
        assert_eq!(format!("{}", pos), "100+5");
        assert!(pos.is_intronic());

        let pos = CdsPos::with_offset(100, -5);
        assert_eq!(format!("{}", pos), "100-5");
        assert!(pos.is_intronic());
    }

    #[test]
    fn test_cds_pos_utr3() {
        let pos = CdsPos::utr3(50);
        assert_eq!(format!("{}", pos), "*50");
        assert!(pos.is_3utr());
    }

    #[test]
    fn test_cds_pos_5utr() {
        let pos = CdsPos::new(-10);
        assert!(pos.is_5utr());
    }

    #[test]
    fn cds_pos_special_is_not_5utr() {
        assert!(!CdsPos::pter().is_5utr(), "pter is not 5'UTR");
        assert!(!CdsPos::qter().is_5utr());
        // A genuine 5'UTR position still is.
        assert!(CdsPos::new(-5).is_5utr());
    }

    #[test]
    fn test_prot_pos_display() {
        let pos = ProtPos::new(AminoAcid::Met, 1);
        assert_eq!(format!("{}", pos), "Met1");
    }

    #[test]
    fn test_prot_pos_fmt_styled() {
        let pos = ProtPos::new(AminoAcid::Ser, 4);
        let one = ProteinRenderStyle {
            stop: TerStyle::Ter,
            aa_code: AaCode::One,
        };
        assert_eq!(
            format!("{}", StyledProtPos(pos, ProteinRenderStyle::default())),
            "Ser4"
        );
        assert_eq!(format!("{}", StyledProtPos(pos, one)), "S4");
        // position-side stop styles via the same rule
        let ter = ProtPos::new(AminoAcid::Ter, 110);
        let three_star = ProteinRenderStyle {
            stop: TerStyle::Star,
            aa_code: AaCode::Three,
        };
        assert_eq!(format!("{}", StyledProtPos(ter, three_star)), "*110");
        // default equals plain Display
        assert_eq!(
            format!("{}", StyledProtPos(pos, ProteinRenderStyle::default())),
            format!("{}", pos)
        );
    }

    #[test]
    fn test_protein_render_style_ter_token() {
        use ProteinRenderStyle as S;
        assert_eq!(
            S {
                stop: TerStyle::Ter,
                aa_code: AaCode::Three
            }
            .ter_token(),
            "Ter"
        );
        assert_eq!(
            S {
                stop: TerStyle::Star,
                aa_code: AaCode::Three
            }
            .ter_token(),
            "*"
        );
        // one-letter forces `*` regardless of the stop toggle
        assert_eq!(
            S {
                stop: TerStyle::Ter,
                aa_code: AaCode::One
            }
            .ter_token(),
            "*"
        );
        assert_eq!(
            S {
                stop: TerStyle::Star,
                aa_code: AaCode::One
            }
            .ter_token(),
            "*"
        );
        assert_eq!(S::default().ter_token(), "Ter");
    }

    #[test]
    fn test_amino_acid_fmt_styled() {
        fn render(aa: AminoAcid, style: ProteinRenderStyle) -> String {
            struct W(AminoAcid, ProteinRenderStyle);
            impl std::fmt::Display for W {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    self.0.fmt_styled(f, self.1)
                }
            }
            format!("{}", W(aa, style))
        }
        let three = ProteinRenderStyle {
            stop: TerStyle::Ter,
            aa_code: AaCode::Three,
        };
        let three_star = ProteinRenderStyle {
            stop: TerStyle::Star,
            aa_code: AaCode::Three,
        };
        let one = ProteinRenderStyle {
            stop: TerStyle::Ter,
            aa_code: AaCode::One,
        };
        assert_eq!(render(AminoAcid::Ser, three), "Ser");
        assert_eq!(render(AminoAcid::Ser, one), "S");
        assert_eq!(render(AminoAcid::Ter, three), "Ter");
        assert_eq!(render(AminoAcid::Ter, three_star), "*");
        assert_eq!(render(AminoAcid::Ter, one), "*");
        // default equals plain Display
        assert_eq!(
            render(AminoAcid::Gln, ProteinRenderStyle::default()),
            format!("{}", AminoAcid::Gln)
        );
    }

    #[test]
    fn test_amino_acid_codes() {
        let aa = AminoAcid::Met;
        assert_eq!(aa.to_three_letter(), "Met");
        assert_eq!(aa.to_one_letter(), 'M');
        assert_eq!(AminoAcid::from_three_letter("Met"), Some(AminoAcid::Met));
    }

    #[test]
    fn test_ivs_pos_new() {
        let pos = IvsPos::new(1, 5);
        assert_eq!(pos.intron, 1);
        assert_eq!(pos.offset, 5);
        assert!(pos.is_5prime());
        assert!(!pos.is_3prime());
    }

    #[test]
    fn test_ivs_pos_display() {
        // 5' boundary notation
        let pos = IvsPos::new(1, 5);
        assert_eq!(format!("{}", pos), "IVS1+5");

        // 3' boundary notation
        let pos = IvsPos::new(2, -10);
        assert_eq!(format!("{}", pos), "IVS2-10");
    }

    #[test]
    fn test_ivs_pos_to_cds_pos() {
        let ivs = IvsPos::new(1, 5);
        let cds = ivs.to_cds_pos(100, false);

        assert_eq!(cds.base, 100);
        assert_eq!(cds.offset, Some(5));
        assert!(!cds.utr3);
    }

    #[test]
    fn test_ivs_pos_deep_intronic() {
        let shallow = IvsPos::new(1, 10);
        assert!(!shallow.is_deep_intronic());
        assert!(!shallow.is_canonical_splice_site());

        let canonical = IvsPos::new(1, 2);
        assert!(canonical.is_canonical_splice_site());

        let deep = IvsPos::new(1, 100);
        assert!(deep.is_deep_intronic());
    }

    #[test]
    fn test_cds_pos_to_ivs() {
        let cds = CdsPos::with_offset(100, 5);
        let ivs = cds.to_ivs(1);

        assert!(ivs.is_some());
        let ivs = ivs.unwrap();
        assert_eq!(ivs.intron, 1);
        assert_eq!(ivs.offset, 5);
    }

    #[test]
    fn test_cds_pos_to_ivs_non_intronic() {
        let cds = CdsPos::new(100); // No offset
        let ivs = cds.to_ivs(1);

        assert!(ivs.is_none());
    }

    #[test]
    fn test_ivs_notation_trait() {
        let intronic_cds = CdsPos::with_offset(100, 5);
        assert!(intronic_cds.has_ivs_notation());

        let exonic_cds = CdsPos::new(100);
        assert!(!exonic_cds.has_ivs_notation());

        let intronic_tx = TxPos::with_offset(100, -10);
        assert!(intronic_tx.has_ivs_notation());
    }

    #[test]
    fn cds_pos_special_is_not_unknown_and_displays_marker() {
        let pter = CdsPos::pter();
        assert!(pter.is_special());
        assert!(!pter.is_unknown(), "special must not be is_unknown");
        assert_eq!(format!("{pter}"), "pter");
        assert_eq!(format!("{}", CdsPos::qter()), "qter");
        assert_eq!(format!("{}", CdsPos::cen()), "cen");
        let unk = CdsPos::unknown(None);
        assert!(unk.is_unknown());
        assert_eq!(format!("{unk}"), "?");
    }
}