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
//! VCF conversion endpoints - bidirectional VCF ↔ HGVS conversion

use axum::{extract::State, http::StatusCode, response::Json};
use std::sync::Arc;
use std::time::Instant;

use crate::data::cdot::{CdotMapper, CdsPosition};
use crate::reference::Strand;
use crate::service::handlers::tx_position::resolve_tx_start;
use crate::service::{
    server::AppState,
    types::{
        ErrorResponse, GenomeBuild, HgvsToVcfRequest, HgvsToVcfResponse, ServiceError, VcfRecord,
        VcfToHgvsRequest, VcfToHgvsResponse,
    },
    validation::validate_hgvs,
};

/// Convert VCF record to HGVS notation
///
/// This endpoint converts a VCF-style variant representation (CHROM, POS, REF, ALT)
/// to HGVS notation. Optionally provide a transcript for c. notation.
pub async fn vcf_to_hgvs(
    State(state): State<AppState>,
    Json(request): Json<VcfToHgvsRequest>,
) -> Result<Json<VcfToHgvsResponse>, (StatusCode, Json<ErrorResponse>)> {
    let start = Instant::now();

    // Validate inputs
    if request.ref_allele.is_empty() {
        let error = ServiceError::BadRequest("ref allele cannot be empty".to_string());
        return Err((
            StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(error.to_response()),
        ));
    }
    if request.alt.is_empty() {
        let error = ServiceError::BadRequest("alt allele cannot be empty".to_string());
        return Err((
            StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(error.to_response()),
        ));
    }

    let vcf = VcfRecord {
        chrom: request.chrom.clone(),
        pos: request.pos,
        ref_allele: request.ref_allele.clone(),
        alt: request.alt.clone(),
        build: request.build.as_str().to_string(),
    };

    // Convert VCF to HGVS
    let (hgvs_g, hgvs_c, hgvs_p, error) = convert_vcf_to_hgvs(
        &request.chrom,
        request.pos,
        &request.ref_allele,
        &request.alt,
        &request.build,
        request.transcript.as_deref(),
        state.cdot.as_ref(),
    );

    let elapsed_ms = start.elapsed().as_millis() as u64;

    Ok(Json(VcfToHgvsResponse {
        vcf,
        hgvs_g,
        hgvs_c,
        hgvs_p,
        error,
        processing_time_ms: elapsed_ms,
    }))
}

/// Convert HGVS notation to VCF record
///
/// This endpoint converts an HGVS variant to VCF-style representation.
pub async fn hgvs_to_vcf(
    State(state): State<AppState>,
    Json(request): Json<HgvsToVcfRequest>,
) -> Result<Json<HgvsToVcfResponse>, (StatusCode, Json<ErrorResponse>)> {
    let start = Instant::now();

    // Validate input HGVS
    if let Err(validation_error) = validate_hgvs(&request.hgvs) {
        let error = ServiceError::InvalidHgvs(validation_error.to_string());
        return Err((
            StatusCode::from_u16(error.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            Json(error.to_response()),
        ));
    }

    // Parse the input HGVS
    let hgvs_str = request.hgvs.clone();
    let parse_result =
        tokio::task::spawn_blocking(move || crate::hgvs::parser::parse_hgvs_lenient(&hgvs_str))
            .await
            .map_err(|e| {
                let error = ServiceError::InternalError(format!("Task error: {}", e));
                (StatusCode::INTERNAL_SERVER_ERROR, Json(error.to_response()))
            })?;

    let elapsed_ms = start.elapsed().as_millis() as u64;

    match parse_result {
        Ok(result) => {
            let (vcf, error) =
                convert_hgvs_to_vcf(&result.result, &request.build, state.cdot.as_ref());

            Ok(Json(HgvsToVcfResponse {
                input: request.hgvs,
                vcf,
                error,
                processing_time_ms: elapsed_ms,
            }))
        }
        Err(e) => Ok(Json(HgvsToVcfResponse {
            input: request.hgvs,
            vcf: None,
            error: Some(format!("Failed to parse input: {}", e)),
            processing_time_ms: elapsed_ms,
        })),
    }
}

/// Convert VCF fields to HGVS notation
fn convert_vcf_to_hgvs(
    chrom: &str,
    pos: u64,
    ref_allele: &str,
    alt: &str,
    build: &GenomeBuild,
    transcript: Option<&str>,
    cdot: Option<&Arc<CdotMapper>>,
) -> (
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
) {
    // Get RefSeq accession for the chromosome
    let accession = match get_refseq_accession(chrom, build) {
        Some(acc) => acc,
        None => {
            return (
                None,
                None,
                None,
                Some(format!("Unknown chromosome: {}", chrom)),
            );
        }
    };

    // Determine variant type and generate genomic HGVS
    let (hgvs_g, variant_type, _variant_pos) =
        generate_genomic_hgvs(&accession, pos, ref_allele, alt);

    // c. and p. notation require transcript mapping
    let (hgvs_c, hgvs_p, tx_error) = if let Some(tx_id) = transcript {
        convert_to_transcript_notation(pos, ref_allele, alt, tx_id, cdot, &variant_type)
    } else {
        (None, None, None)
    };

    // Combine errors
    let error = if transcript.is_some() && hgvs_c.is_none() && tx_error.is_some() {
        tx_error
    } else {
        None
    };

    (hgvs_g, hgvs_c, hgvs_p, error)
}

/// Variant type for internal use
#[derive(Debug, Clone)]
enum VariantType {
    Substitution,
    Deletion,
    Insertion,
    Delins,
    Unknown,
}

/// Generate genomic HGVS notation from VCF fields
fn generate_genomic_hgvs(
    accession: &str,
    pos: u64,
    ref_allele: &str,
    alt: &str,
) -> (Option<String>, VariantType, u64) {
    if ref_allele.len() == 1 && alt.len() == 1 && ref_allele != alt {
        // Simple substitution
        let hgvs = format!("{}:g.{}{}>{}", accession, pos, ref_allele, alt);
        (Some(hgvs), VariantType::Substitution, pos)
    } else if ref_allele.len() > alt.len() && alt.len() == 1 && ref_allele.starts_with(alt) {
        // Deletion (VCF style with padding base)
        let del_start = pos + 1;
        let del_end = pos + (ref_allele.len() - 1) as u64;
        let hgvs = if del_start == del_end {
            format!("{}:g.{}del", accession, del_start)
        } else {
            format!("{}:g.{}_{}del", accession, del_start, del_end)
        };
        (Some(hgvs), VariantType::Deletion, del_start)
    } else if alt.len() > ref_allele.len() && ref_allele.len() == 1 && alt.starts_with(ref_allele) {
        // Insertion (VCF style with padding base)
        let inserted = &alt[1..];
        let hgvs = format!("{}:g.{}_{}ins{}", accession, pos, pos + 1, inserted);
        (Some(hgvs), VariantType::Insertion, pos)
    } else if ref_allele != alt {
        // Delins
        let hgvs = format!("{}:g.{}delins{}", accession, pos, alt);
        (Some(hgvs), VariantType::Delins, pos)
    } else {
        (None, VariantType::Unknown, pos)
    }
}

/// Convert genomic position to transcript (c.) and protein (p.) notation
fn convert_to_transcript_notation(
    genomic_pos: u64,
    ref_allele: &str,
    alt: &str,
    transcript_id: &str,
    cdot: Option<&Arc<CdotMapper>>,
    variant_type: &VariantType,
) -> (Option<String>, Option<String>, Option<String>) {
    // Need cdot data for transcript lookups
    let cdot = match cdot {
        Some(c) => c,
        None => {
            return (
                None,
                None,
                Some(
                    "Transcript mapping requires cdot data. Configure 'data.cdot_path' in settings."
                        .to_string(),
                ),
            );
        }
    };

    // Get the transcript
    let cdot_tx = match cdot.get_transcript(transcript_id) {
        Some(tx) => tx,
        None => {
            return (
                None,
                None,
                Some(format!(
                    "Transcript {} not found in cdot data",
                    transcript_id
                )),
            );
        }
    };

    // Try to convert genomic position to transcript position
    let tx_pos = match cdot_tx.genome_to_tx(genomic_pos) {
        Some(pos) => pos,
        None => {
            return (
                None,
                None,
                Some(format!(
                    "Genomic position {} not found in transcript {} exons",
                    genomic_pos, transcript_id
                )),
            );
        }
    };

    // Convert to CDS position if available
    let cds_pos = cdot_tx.tx_to_cds(tx_pos);

    // Generate c. notation
    let hgvs_c = generate_cds_hgvs(
        transcript_id,
        cds_pos.as_ref(),
        variant_type,
        ref_allele,
        alt,
    );

    // Generate p. notation for coding variants (if applicable)
    let hgvs_p = match &cds_pos {
        Some(CdsPosition::Cds(base)) if *base > 0 => {
            // Calculate protein position: (cds_pos - 1) / 3 + 1
            let prot_position = ((*base - 1) / 3 + 1) as u64;
            // Reaching this arm already proves the variant is in the CDS:
            // `tx_to_cds` returns `Some(CdsPosition::Cds(_))` only for a
            // transcript that has CDS bounds (`cds_start`/`cds_end` present) and
            // a position inside them. A non-coding transcript (no `cds_start`)
            // yields `None` and falls through to the `_ => None` arm below, so no
            // prefix gate is needed to suppress its `p.`.
            //
            // Protein accession: the authoritative cdot value if present, else
            // the transcript accession itself. We do NOT infer `NP_*`/`XP_*`
            // from `NM_*`/`XM_*` by preserving the number — RefSeq does not
            // guarantee the NM and NP numbers match, so that is frequently
            // wrong (#808). Emitting unconditionally here also keeps the `p.`
            // for coding `ENST_`/custom transcripts that have CDS bounds but no
            // authoritative `cdot.protein`.
            let prot_acc = cdot_tx
                .protein
                .clone()
                .unwrap_or_else(|| transcript_id.to_string());
            Some(format!("{}:p.{}", prot_acc, prot_position))
        }
        _ => None, // UTR, intronic, or non-coding (no CDS) variant
    };

    (hgvs_c, hgvs_p, None)
}

/// Generate c. HGVS notation from CDS position
fn generate_cds_hgvs(
    transcript_id: &str,
    cds_pos: Option<&CdsPosition>,
    variant_type: &VariantType,
    ref_allele: &str,
    alt: &str,
) -> Option<String> {
    let pos_str = match cds_pos {
        Some(CdsPosition::Cds(base)) => format!("{}", base),
        Some(CdsPosition::FivePrimeUtr(offset)) => format!("-{}", offset),
        Some(CdsPosition::ThreePrimeUtr(offset)) => format!("*{}", offset),
        None => return None, // Can't generate c. without CDS info
    };

    let edit_str = match variant_type {
        VariantType::Substitution => {
            format!("{}>{}", ref_allele, alt)
        }
        VariantType::Deletion => "del".to_string(),
        VariantType::Insertion => {
            let inserted = if alt.len() > 1 { &alt[1..] } else { alt };
            format!("ins{}", inserted)
        }
        VariantType::Delins => format!("delins{}", alt),
        VariantType::Unknown => return None,
    };

    Some(format!("{}:c.{}{}", transcript_id, pos_str, edit_str))
}

/// Convert parsed HGVS to VCF record
fn convert_hgvs_to_vcf(
    variant: &crate::hgvs::variant::HgvsVariant,
    build: &GenomeBuild,
    cdot: Option<&Arc<CdotMapper>>,
) -> (Option<VcfRecord>, Option<String>) {
    use crate::hgvs::variant::HgvsVariant;

    match variant {
        HgvsVariant::Genome(v) => {
            // Extract chromosome from accession
            let chrom = extract_chromosome_from_accession(&v.accession.to_string());

            // Extract position and alleles from the edit
            if let Some(edit) = v.loc_edit.edit.inner() {
                let (pos, ref_allele, alt) = extract_vcf_fields(edit, &v.loc_edit.location);

                if let (Some(pos), Some(ref_a), Some(alt_a)) = (pos, ref_allele, alt) {
                    return (
                        Some(VcfRecord {
                            chrom,
                            pos,
                            ref_allele: ref_a,
                            alt: alt_a,
                            build: build.as_str().to_string(),
                        }),
                        None,
                    );
                }
            }

            (
                None,
                Some("Could not extract VCF fields from variant".to_string()),
            )
        }
        HgvsVariant::Cds(v) => {
            // c. variant - need coordinate conversion to g.
            let accession = v.accession.to_string();
            convert_cds_to_vcf(&accession, &v.loc_edit, build, cdot)
        }
        HgvsVariant::Tx(v) => {
            // n. variant - need coordinate conversion to g.
            let accession = v.accession.to_string();
            convert_tx_to_vcf(&accession, &v.loc_edit, build, cdot)
        }
        _ => (
            None,
            Some("VCF conversion is only supported for g., c., and n. variants".to_string()),
        ),
    }
}

/// Convert c. variant to VCF via coordinate mapping
///
/// Handles both exonic and intronic variants:
/// - Exonic: c.350C>T - position within CDS
/// - Intronic: c.117-2del - position 2 bases into intron before exon position 117
fn convert_cds_to_vcf(
    transcript_id: &str,
    loc_edit: &crate::hgvs::variant::LocEdit<
        crate::hgvs::interval::CdsInterval,
        crate::hgvs::edit::NaEdit,
    >,
    build: &GenomeBuild,
    cdot: Option<&Arc<CdotMapper>>,
) -> (Option<VcfRecord>, Option<String>) {
    // Need cdot for coordinate conversion
    let cdot = match cdot {
        Some(c) => c,
        None => {
            return (
                None,
                Some(
                    "Converting c. to VCF requires cdot data. Configure 'data.cdot_path' in settings."
                        .to_string(),
                ),
            );
        }
    };

    // Get transcript
    let cdot_tx = match cdot.get_transcript(transcript_id) {
        Some(tx) => tx,
        None => {
            return (
                None,
                Some(format!("Transcript {} not found", transcript_id)),
            );
        }
    };

    // Extract CDS position and intronic offset
    let (cds_base, offset) = match loc_edit.location.start.inner() {
        Some(p) => (p.base, p.offset),
        None => (1, None),
    };

    // Convert CDS to transcript position
    let tx_pos = match cdot_tx.cds_to_tx(cds_base) {
        Some(pos) => pos,
        None => {
            return (
                None,
                Some("Could not convert CDS to transcript position".to_string()),
            );
        }
    };

    // Handle intronic offset if present (e.g., c.117-2del has offset -2)
    let genomic_pos = if let Some(intron_offset) = offset {
        // This is an intronic variant
        // Get the exon boundary genomic position first
        let exon_boundary_pos = match cdot_tx.tx_to_genome(tx_pos) {
            Some(pos) => pos,
            None => {
                return (None, Some("Exon boundary position not found".to_string()));
            }
        };

        // Apply intron offset based on strand orientation
        // Negative offset (e.g., -2) means position is before the exon in the intron
        // Positive offset (e.g., +5) means position is after the exon in the intron
        match cdot_tx.strand {
            Strand::Plus => {
                if intron_offset < 0 {
                    // Position is before exon (5' splice site)
                    // e.g., c.117-2 is 2 bases before position 117 in the transcript
                    exon_boundary_pos.saturating_sub((-intron_offset) as u64)
                } else {
                    // Position is after exon (3' splice site)
                    exon_boundary_pos.saturating_add(intron_offset as u64)
                }
            }
            Strand::Minus => {
                if intron_offset < 0 {
                    // On minus strand, negative offset goes in positive genomic direction
                    exon_boundary_pos.saturating_add((-intron_offset) as u64)
                } else {
                    // Positive offset goes in negative genomic direction
                    exon_boundary_pos.saturating_sub(intron_offset as u64)
                }
            }
            Strand::Unknown => {
                return (
                    None,
                    Some(format!(
                        "Cannot convert intronic CDS position for transcript {}: \
                         unknown strand",
                        transcript_id
                    )),
                );
            }
        }
    } else {
        // Exonic variant - direct conversion
        match cdot_tx.tx_to_genome(tx_pos) {
            Some(pos) => pos,
            None => {
                return (None, Some("Position not found in exons".to_string()));
            }
        }
    };

    // Get chromosome
    let chrom = cdot_tx.contig.clone();

    // Extract alleles from edit
    if let Some(edit) = loc_edit.edit.inner() {
        let (ref_allele, alt) = extract_alleles_from_edit(edit);
        if let (Some(ref_a), Some(alt_a)) = (ref_allele, alt) {
            // Add warning for intronic variants using placeholder bases
            let warning = if offset.is_some() {
                Some("Intronic variant: VCF position calculated from intron offset. Reference allele may need verification.".to_string())
            } else {
                None
            };

            return (
                Some(VcfRecord {
                    chrom,
                    pos: genomic_pos,
                    ref_allele: ref_a,
                    alt: alt_a,
                    build: build.as_str().to_string(),
                }),
                warning,
            );
        }
    }

    (
        None,
        Some("Could not extract alleles from variant".to_string()),
    )
}

/// Convert n. variant to VCF via coordinate mapping
fn convert_tx_to_vcf(
    transcript_id: &str,
    loc_edit: &crate::hgvs::variant::LocEdit<
        crate::hgvs::interval::TxInterval,
        crate::hgvs::edit::NaEdit,
    >,
    build: &GenomeBuild,
    cdot: Option<&Arc<CdotMapper>>,
) -> (Option<VcfRecord>, Option<String>) {
    // Need cdot for coordinate conversion
    let cdot = match cdot {
        Some(c) => c,
        None => {
            return (
                None,
                Some(
                    "Converting n. to VCF requires cdot data. Configure 'data.cdot_path' in settings."
                        .to_string(),
                ),
            );
        }
    };

    // Get transcript
    let cdot_tx = match cdot.get_transcript(transcript_id) {
        Some(tx) => tx,
        None => {
            return (
                None,
                Some(format!("Transcript {} not found", transcript_id)),
            );
        }
    };

    // Extract transcript position. `resolve_tx_start` refuses `n.*N`: reading
    // `base` alone made `n.5` and `n.*5` resolve to the same coordinate, so
    // this emitted a whole VCF record for a different nucleotide with no
    // diagnostic.
    let tx_pos = match resolve_tx_start(&loc_edit.location) {
        Ok(pos) => pos,
        Err(msg) => return (None, Some(msg)),
    };

    // Convert to genomic
    let genomic_pos = match cdot_tx.tx_to_genome(tx_pos) {
        Some(pos) => pos,
        None => {
            return (None, Some("Position not found in exons".to_string()));
        }
    };

    // Get chromosome
    let chrom = cdot_tx.contig.clone();

    // Extract alleles from edit
    if let Some(edit) = loc_edit.edit.inner() {
        let (ref_allele, alt) = extract_alleles_from_edit(edit);
        if let (Some(ref_a), Some(alt_a)) = (ref_allele, alt) {
            return (
                Some(VcfRecord {
                    chrom,
                    pos: genomic_pos,
                    ref_allele: ref_a,
                    alt: alt_a,
                    build: build.as_str().to_string(),
                }),
                None,
            );
        }
    }

    (
        None,
        Some("Could not extract alleles from variant".to_string()),
    )
}

/// Extract alleles from HGVS edit
///
/// VCF format requires a "padding" base for indels. When sequence data is not available,
/// "N" is used as a placeholder. The returned alleles are suitable for VCF but may need
/// reference lookup for accurate representation.
///
/// Returns (ref_allele, alt_allele) where either may be None if extraction fails.
fn extract_alleles_from_edit(edit: &crate::hgvs::edit::NaEdit) -> (Option<String>, Option<String>) {
    use crate::hgvs::edit::NaEdit;

    match edit {
        NaEdit::Substitution {
            reference,
            alternative,
        } => (Some(reference.to_string()), Some(alternative.to_string())),
        NaEdit::SubstitutionNoRef { alternative } => {
            // Reference base not specified in HGVS - use "N" placeholder
            // Accurate VCF requires fetching reference sequence
            (Some("N".to_string()), Some(alternative.to_string()))
        }
        NaEdit::Deletion { sequence, .. } => {
            if let Some(seq) = sequence {
                // VCF requires padding base before deletion
                // "N" is placeholder - accurate VCF needs reference lookup
                (Some(format!("N{}", seq)), Some("N".to_string()))
            } else {
                // Deletion without explicit sequence cannot be converted without reference
                (None, None)
            }
        }
        NaEdit::Insertion { sequence } => {
            // VCF requires padding base before insertion
            // "N" is placeholder - accurate VCF needs reference lookup
            (Some("N".to_string()), Some(format!("N{}", sequence)))
        }
        NaEdit::Delins { sequence, .. } => {
            // Delins without original sequence - use "N" placeholder for ref
            (Some("N".to_string()), Some(sequence.to_string()))
        }
        NaEdit::Duplication { sequence, .. } => {
            if let Some(seq) = sequence {
                (Some(seq.to_string()), Some(format!("{}{}", seq, seq)))
            } else {
                (None, None)
            }
        }
        _ => (None, None),
    }
}

/// Extract VCF fields from HGVS edit
fn extract_vcf_fields(
    edit: &crate::hgvs::edit::NaEdit,
    location: &crate::hgvs::interval::GenomeInterval,
) -> (Option<u64>, Option<String>, Option<String>) {
    let pos = location.start.inner().map(|p| p.base);
    let (ref_allele, alt) = extract_alleles_from_edit(edit);
    (pos, ref_allele, alt)
}

/// Get RefSeq accession for a chromosome and build
fn get_refseq_accession(chrom: &str, build: &GenomeBuild) -> Option<String> {
    let chrom_normalized = chrom.trim_start_matches("chr");
    let chrom_num = chrom_normalized
        .parse::<u32>()
        .ok()
        .or(match chrom_normalized {
            "X" => Some(23),
            "Y" => Some(24),
            "M" | "MT" => Some(12920),
            _ => None,
        })?;

    let version = match build {
        GenomeBuild::GRCh37 => match chrom_num {
            1 => "10",
            2 => "11",
            3 => "11",
            4 => "11",
            5 => "9",
            6 => "11",
            7 => "13",
            8 => "10",
            9 => "11",
            10 => "10",
            11 => "9",
            12 => "11",
            13 => "10",
            14 => "8",
            15 => "9",
            16 => "9",
            17 => "10",
            18 => "9",
            19 => "9",
            20 => "10",
            21 => "8",
            22 => "10",
            23 => "10",
            24 => "9",
            12920 => "1",
            _ => return None,
        },
        GenomeBuild::GRCh38 => match chrom_num {
            1 => "11",
            2 => "12",
            3 => "12",
            4 => "12",
            5 => "10",
            6 => "12",
            7 => "14",
            8 => "11",
            9 => "12",
            10 => "11",
            11 => "10",
            12 => "12",
            13 => "11",
            14 => "9",
            15 => "10",
            16 => "10",
            17 => "11",
            18 => "10",
            19 => "10",
            20 => "11",
            21 => "9",
            22 => "11",
            23 => "11",
            24 => "10",
            12920 => "1",
            _ => return None,
        },
    };

    if chrom_num == 12920 {
        Some(format!("NC_012920.{}", version))
    } else {
        Some(format!("NC_{:06}.{}", chrom_num, version))
    }
}

/// Extract the UCSC chromosome name from a RefSeq accession.
///
/// Resolves the primary-assembly `NC_` → UCSC mapping through the shared,
/// build-aware [`ContigAliases`](crate::liftover::aliases::ContigAliases)
/// reverse table rather than a hand-rolled accession ladder, so the forward and
/// reverse directions share one source of truth. Accessions the table does not
/// describe are returned unchanged.
fn extract_chromosome_from_accession(accession: &str) -> String {
    crate::liftover::aliases::default_human_aliases()
        .refseq_to_ucsc(accession)
        .map(|ucsc| ucsc.to_string())
        .unwrap_or_else(|| accession.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::cdot::CdotTranscript;
    use crate::hgvs::edit::{Base, NaEdit};
    use crate::hgvs::interval::TxInterval;
    use crate::hgvs::location::TxPos;
    use crate::hgvs::variant::LocEdit;

    /// One 9-base exon at genome 1000..1009, so every `n.` base in range maps
    /// to a genomic coordinate and a divergence cannot be an artifact of the
    /// exon walk declining.
    fn single_exon_mapper() -> Arc<CdotMapper> {
        let mut cdot = CdotMapper::new();
        cdot.add_transcript(
            "NM_TEST.1".to_string(),
            CdotTranscript {
                cds_start_incomplete: false,
                gene_name: Some("TESTGENE".to_string()),
                contig: "chr1".to_string(),
                strand: Strand::Plus,
                exons: vec![[1000, 1009, 0, 9]],
                cds_start: Some(0),
                cds_end: Some(9),
                gene_id: None,
                protein: Some("NP_TEST.1".to_string()),
                exon_cigars: Vec::new(),
            },
        );
        Arc::new(cdot)
    }

    /// The second drop route, at the handler seam: `n.5` and `n.*5` are
    /// different nucleotides, so the VCF record emitted for them must not be
    /// the same.
    ///
    /// Before the fix this read `base` alone, so both sides emitted a record at
    /// the genomic coordinate of in-transcript base 5 — a *collapse*, and one
    /// that leaves the wrong `POS` in a VCF with no diagnostic. Asserted as a
    /// divergence rather than against a pinned message so it cannot be
    /// satisfied by a wording change.
    #[test]
    fn n_to_vcf_does_not_emit_a_downstream_position_as_its_in_transcript_twin() {
        let cdot = single_exon_mapper();
        let edit = || NaEdit::Substitution {
            reference: Base::C,
            alternative: Base::A,
        };
        let convert = |pos: TxPos| {
            convert_tx_to_vcf(
                "NM_TEST.1",
                &LocEdit::new(TxInterval::point(pos), edit()),
                &GenomeBuild::GRCh38,
                Some(&cdot),
            )
        };

        let (plain, plain_err) = convert(TxPos::new(5));
        let (downstream, downstream_err) = convert(TxPos::downstream(5));

        assert!(
            plain.is_some() && plain_err.is_none(),
            "control: a plain in-transcript n.5 must still emit a record, \
             got {plain:?} / {plain_err:?}"
        );
        assert_ne!(
            plain.map(|r| r.pos),
            downstream.as_ref().map(|r| r.pos),
            "n.5 and n.*5 are different nucleotides and must not emit the same POS"
        );
        assert!(
            downstream.is_none(),
            "n.*5 names a nucleotide past the transcript's last base and has no \
             genomic position; the handler emitted {downstream:?} instead of refusing"
        );
        assert!(
            downstream_err.is_some_and(|m| m.contains("n.*")),
            "the decline must name the notation it refused"
        );
    }

    #[test]
    fn test_get_refseq_accession_grch38() {
        assert_eq!(
            get_refseq_accession("chr7", &GenomeBuild::GRCh38),
            Some("NC_000007.14".to_string())
        );
        assert_eq!(
            get_refseq_accession("7", &GenomeBuild::GRCh38),
            Some("NC_000007.14".to_string())
        );
        assert_eq!(
            get_refseq_accession("chrX", &GenomeBuild::GRCh38),
            Some("NC_000023.11".to_string())
        );
    }

    #[test]
    fn test_get_refseq_accession_grch37() {
        assert_eq!(
            get_refseq_accession("chr7", &GenomeBuild::GRCh37),
            Some("NC_000007.13".to_string())
        );
        assert_eq!(
            get_refseq_accession("chr1", &GenomeBuild::GRCh37),
            Some("NC_000001.10".to_string())
        );
    }

    #[test]
    fn test_extract_chromosome_from_accession() {
        assert_eq!(extract_chromosome_from_accession("NC_000007.14"), "chr7");
        assert_eq!(extract_chromosome_from_accession("NC_000001.11"), "chr1");
        assert_eq!(extract_chromosome_from_accession("NC_000023.11"), "chrX");
        assert_eq!(extract_chromosome_from_accession("NC_000024.10"), "chrY");
        assert_eq!(extract_chromosome_from_accession("NC_012920.1"), "chrM");
    }

    #[test]
    fn test_extract_chromosome_from_accession_unmapped_passthrough() {
        // An accession the shared alias table does not know is returned
        // unchanged rather than being coerced to a fabricated chrN.
        assert_eq!(
            extract_chromosome_from_accession("NC_000025.11"),
            "NC_000025.11"
        );
        assert_eq!(
            extract_chromosome_from_accession("NW_009646201.1"),
            "NW_009646201.1"
        );
    }

    #[test]
    fn test_generate_genomic_hgvs_substitution() {
        let (hgvs, var_type, pos) = generate_genomic_hgvs("NC_000007.14", 117559593, "G", "A");
        assert_eq!(hgvs, Some("NC_000007.14:g.117559593G>A".to_string()));
        assert!(matches!(var_type, VariantType::Substitution));
        assert_eq!(pos, 117559593);
    }

    #[test]
    fn test_generate_genomic_hgvs_deletion() {
        let (hgvs, var_type, _) = generate_genomic_hgvs("NC_000007.14", 117559592, "AG", "A");
        assert_eq!(hgvs, Some("NC_000007.14:g.117559593del".to_string()));
        assert!(matches!(var_type, VariantType::Deletion));
    }

    #[test]
    fn test_generate_genomic_hgvs_multi_deletion() {
        let (hgvs, var_type, _) = generate_genomic_hgvs("NC_000007.14", 117559592, "AGT", "A");
        assert_eq!(
            hgvs,
            Some("NC_000007.14:g.117559593_117559594del".to_string())
        );
        assert!(matches!(var_type, VariantType::Deletion));
    }

    #[test]
    fn test_generate_genomic_hgvs_insertion() {
        let (hgvs, var_type, _) = generate_genomic_hgvs("NC_000007.14", 117559593, "G", "GA");
        assert_eq!(
            hgvs,
            Some("NC_000007.14:g.117559593_117559594insA".to_string())
        );
        assert!(matches!(var_type, VariantType::Insertion));
    }

    #[test]
    fn test_unknown_chromosome() {
        assert_eq!(get_refseq_accession("chrW", &GenomeBuild::GRCh38), None);
        assert_eq!(get_refseq_accession("unknown", &GenomeBuild::GRCh37), None);
    }

    #[test]
    fn test_vcf_to_hgvs_without_cdot() {
        // Without cdot, should still produce g. notation but not c./p.
        let (hgvs_g, hgvs_c, hgvs_p, error) = convert_vcf_to_hgvs(
            "chr7",
            117559593,
            "G",
            "A",
            &GenomeBuild::GRCh38,
            Some("NM_000249.4"),
            None,
        );

        assert!(hgvs_g.is_some());
        assert_eq!(hgvs_g.unwrap(), "NC_000007.14:g.117559593G>A");
        assert!(hgvs_c.is_none());
        assert!(hgvs_p.is_none());
        assert!(error.is_some());
        assert!(error.unwrap().contains("cdot"));
    }

    /// Build a single-transcript cdot mapper on a `chr1`-style contig with the
    /// canonical projector test layout: genome [1000, 1009) (0-based excl) /
    /// tx [0, 9), CDS = whole transcript. `protein` is the authoritative
    /// protein accession or `None`. With this layout genome position 1003
    /// maps to CDS base 4 (protein codon 2).
    #[cfg(test)]
    fn coding_cdot(tx_id: &str, contig: &str, protein: Option<&str>) -> Arc<CdotMapper> {
        use crate::data::cdot::CdotTranscript;
        use crate::reference::Strand;
        let mut mapper = CdotMapper::new();
        mapper.add_transcript(
            tx_id.to_string(),
            CdotTranscript {
                cds_start_incomplete: false,
                gene_name: Some("TESTGENE".to_string()),
                contig: contig.to_string(),
                strand: Strand::Plus,
                exons: vec![[1000, 1009, 0, 9]],
                cds_start: Some(0),
                cds_end: Some(9),
                gene_id: None,
                protein: protein.map(str::to_string),
                exon_cigars: Vec::new(),
            },
        );
        Arc::new(mapper)
    }

    /// Build a CdotMapper for a non-coding transcript: same exon span as
    /// `coding_cdot` but with NO CDS bounds (`cds_start`/`cds_end` are `None`).
    /// `tx_to_cds` returns `None` for such a transcript, so no `p.` is produced —
    /// modeling "non-coding" by the absence of a CDS rather than by accession
    /// prefix (#808).
    fn noncoding_cdot(tx_id: &str, contig: &str) -> Arc<CdotMapper> {
        use crate::data::cdot::CdotTranscript;
        use crate::reference::Strand;
        let mut mapper = CdotMapper::new();
        mapper.add_transcript(
            tx_id.to_string(),
            CdotTranscript {
                cds_start_incomplete: false,
                gene_name: Some("TESTGENE".to_string()),
                contig: contig.to_string(),
                strand: Strand::Plus,
                exons: vec![[1000, 1009, 0, 9]],
                cds_start: None,
                cds_end: None,
                gene_id: None,
                protein: None,
                exon_cigars: Vec::new(),
            },
        );
        Arc::new(mapper)
    }

    #[test]
    fn vcf_convert_p_prefers_authoritative_protein() {
        // When cdot carries the authoritative protein accession, the p. uses
        // it (here NP_000068.1, whose number differs from the NM_).
        let cdot = coding_cdot("NM_000077.4", "chr1", Some("NP_000068.1"));
        let (_c, p, err) = convert_to_transcript_notation(
            1003,
            "C",
            "A",
            "NM_000077.4",
            Some(&cdot),
            &VariantType::Substitution,
        );
        assert!(err.is_none(), "unexpected error: {err:?}");
        assert_eq!(p.as_deref(), Some("NP_000068.1:p.2"));
    }

    #[test]
    fn vcf_convert_p_coding_nm_without_protein_uses_transcript_id_not_inferred_np() {
        // #808: a coding NM_ transcript with no authoritative protein must
        // still emit a p. (it is coding), keyed off the transcript id — NOT a
        // fabricated number-preserving NP_. The old prefix-proxy gate would
        // have emitted NP_000077.4; the rework must not.
        let cdot = coding_cdot("NM_000077.4", "chr1", None);
        let (_c, p, err) = convert_to_transcript_notation(
            1003,
            "C",
            "A",
            "NM_000077.4",
            Some(&cdot),
            &VariantType::Substitution,
        );
        assert!(err.is_none(), "unexpected error: {err:?}");
        assert_eq!(p.as_deref(), Some("NM_000077.4:p.2"));
        assert!(
            !p.as_deref().unwrap().starts_with("NP_"),
            "must not fabricate an NP_: {p:?}"
        );
    }

    #[test]
    fn vcf_convert_p_noncoding_transcript_without_cds_drops_p() {
        // A non-coding transcript — modeled by the ABSENCE of CDS bounds, not by
        // an accession prefix — has no protein product. `tx_to_cds` returns
        // `None`, so no `p.` is emitted. The NR_ accession here is incidental;
        // the suppression is driven by the missing CDS, which is the correct
        // signal (#808).
        let cdot = noncoding_cdot("NR_000077.4", "chr1");
        let (_c, p, err) = convert_to_transcript_notation(
            1003,
            "C",
            "A",
            "NR_000077.4",
            Some(&cdot),
            &VariantType::Substitution,
        );
        assert!(err.is_none(), "unexpected error: {err:?}");
        assert!(
            p.is_none(),
            "transcript without CDS bounds must not emit a p.: {p:?}"
        );
    }

    #[test]
    fn vcf_convert_p_coding_non_nm_transcript_without_protein_emits_p() {
        // A coding transcript whose accession is NOT an NM_/XM_ RefSeq mRNA
        // (e.g. an Ensembl ENST_ or a custom id) but which HAS CDS bounds and no
        // authoritative `cdot.protein` must still emit a `p.`, keyed off the
        // transcript id. The old NM_/XM_ prefix gate wrongly dropped this valid
        // coding `p.` (#808); removing the gate restores it.
        let cdot = coding_cdot("ENST00000367770.5", "chr1", None);
        let (_c, p, err) = convert_to_transcript_notation(
            1003,
            "C",
            "A",
            "ENST00000367770.5",
            Some(&cdot),
            &VariantType::Substitution,
        );
        assert!(err.is_none(), "unexpected error: {err:?}");
        assert_eq!(p.as_deref(), Some("ENST00000367770.5:p.2"));
    }
}