check_build 0.4.0

A tool to verify a VCF file against hg19 and hg38 references using a streaming, low-memory approach.
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
//! # check_build
//!
//! A library and CLI tool to verify VCF files against hg19 and hg38 reference genomes.
//!
//! ## Simplest Usage: "What build is my file?"
//!
//! ```rust,no_run
//! use check_build::detect_build;
//!
//! let result = detect_build("my_file.vcf").unwrap();
//! println!("{}", result);  // e.g., "hg38 (100.0% match)"
//! ```
//!
//! ## Standard Usage
//!
//! ```rust,no_run
//! use check_build::Verifier;
//!
//! let result = Verifier::new("file.vcf")
//!     .verify_both()
//!     .unwrap();
//!
//! println!("hg19: {} mismatches", result.hg19_mismatches);
//! println!("hg38: {} mismatches", result.hg38_mismatches);
//!
//! if let Some(build) = result.likely_build() {
//!     println!("Detected build: {:?}", build);
//! }
//! ```
//!
//! ## Advanced Usage
//!
//! ```rust,no_run
//! use check_build::{Verifier, Reference};
//!
//! // Verify against just one reference
//! let (lines, mismatches) = Verifier::new("file.vcf")
//!     .verify_single(Reference::Hg38)
//!     .unwrap();
//!
//! // Use custom reference paths, no progress output
//! let result = Verifier::new("file.vcf")
//!     .hg19_path("/data/refs/hg19.fa")
//!     .hg38_path("/data/refs/hg38.fa")
//!     .quiet()
//!     .silent()
//!     .verify_both()
//!     .unwrap();
//! ```

use flate2::read::GzDecoder;
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use memchr::memchr;
use rayon::prelude::*;
use reqwest::blocking::Client;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tempfile::TempDir;

// ============================================================================
// Public Constants
// ============================================================================

/// URL for hg19 reference FASTA
pub const HG19_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.gz";
/// URL for hg38 reference FASTA
pub const HG38_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.gz";

/// URL for hg19 md5sum.txt
pub const HG19_MD5_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/md5sum.txt";
/// URL for hg38 md5sum.txt  
pub const HG38_MD5_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/md5sum.txt";

/// Default local filename for hg19
pub const HG19_DEFAULT_PATH: &str = "hg19.fa.gz";
/// Default local filename for hg38
pub const HG38_DEFAULT_PATH: &str = "hg38.fa.gz";

// ============================================================================
// Internal Constants
// ============================================================================

const EXPECTED_MAX_CONTIG_SIZE: usize = 300_000_000;
const DOWNLOAD_BUFFER_SIZE: usize = 131_072;
const FASTA_READ_BUFFER_SIZE: usize = 262_144;

// ============================================================================
// Public Types
// ============================================================================

/// Reference genome to verify against
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reference {
    /// GRCh37/hg19
    Hg19,
    /// GRCh38/hg38
    Hg38,
}

impl Reference {
    /// Get the default download URL for this reference
    pub fn url(&self) -> &'static str {
        match self {
            Reference::Hg19 => HG19_URL,
            Reference::Hg38 => HG38_URL,
        }
    }

    /// Get the URL for the md5sum.txt file containing checksums for this reference
    pub fn md5_url(&self) -> &'static str {
        match self {
            Reference::Hg19 => HG19_MD5_URL,
            Reference::Hg38 => HG38_MD5_URL,
        }
    }

    /// Get the default local filename for this reference
    pub fn default_path(&self) -> &'static str {
        match self {
            Reference::Hg19 => HG19_DEFAULT_PATH,
            Reference::Hg38 => HG38_DEFAULT_PATH,
        }
    }
}

/// A variant position to be verified
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variant {
    /// Chromosome name (e.g., "chr1" or "1")
    pub chrom: String,
    /// 1-based position
    pub pos: u64,
    /// Reference allele
    pub ref_base: String,
}

/// Result of verifying a VCF against both references
#[derive(Debug, Clone, Default)]
pub struct VerificationResult {
    /// Lines verified against hg19
    pub hg19_lines: u64,
    /// Mismatches found against hg19
    pub hg19_mismatches: u64,
    /// Lines verified against hg38
    pub hg38_lines: u64,
    /// Mismatches found against hg38
    pub hg38_mismatches: u64,
}

impl VerificationResult {
    /// Returns true if no mismatches on either reference
    pub fn all_passed(&self) -> bool {
        self.hg19_mismatches == 0 && self.hg38_mismatches == 0
    }

    /// Infer which build the VCF is aligned to based on mismatch patterns
    ///
    /// Returns `Some(Reference::Hg19)` if hg19 has 0 mismatches but hg38 doesn't,
    /// `Some(Reference::Hg38)` if vice versa, or `None` if ambiguous.
    pub fn likely_build(&self) -> Option<Reference> {
        match (self.hg19_mismatches, self.hg38_mismatches) {
            (0, m) if m > 0 => Some(Reference::Hg19),
            (m, 0) if m > 0 => Some(Reference::Hg38),
            _ => None,
        }
    }

    /// Get percentage match rate for a reference
    pub fn match_rate(&self, reference: Reference) -> f64 {
        let (lines, mismatches) = match reference {
            Reference::Hg19 => (self.hg19_lines, self.hg19_mismatches),
            Reference::Hg38 => (self.hg38_lines, self.hg38_mismatches),
        };
        if lines == 0 {
            return 0.0;
        }
        ((lines - mismatches) as f64 / lines as f64) * 100.0
    }
}

/// Result of build detection - just the data, caller interprets
#[derive(Debug, Clone)]
pub struct BuildResult {
    /// Match rate against hg19 (0.0 to 100.0)
    pub hg19_match_rate: f64,
    /// Match rate against hg38 (0.0 to 100.0)
    pub hg38_match_rate: f64,
    /// Lines checked against hg19
    pub hg19_lines: u64,
    /// Lines checked against hg38
    pub hg38_lines: u64,
    /// Mismatches against hg19
    pub hg19_mismatches: u64,
    /// Mismatches against hg38
    pub hg38_mismatches: u64,
}

impl BuildResult {
    /// Returns the build with higher match rate, or None if no data
    pub fn better_match(&self) -> Option<Reference> {
        if self.hg19_lines == 0 && self.hg38_lines == 0 {
            return None;
        }
        if self.hg19_match_rate > self.hg38_match_rate {
            Some(Reference::Hg19)
        } else {
            Some(Reference::Hg38)
        }
    }

    /// Returns true if one build has 0 mismatches and the other doesn't
    pub fn is_clear_match(&self) -> bool {
        (self.hg19_mismatches == 0) != (self.hg38_mismatches == 0)
    }
}

impl std::fmt::Display for BuildResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "hg19: {:.1}% ({}/{} matched), hg38: {:.1}% ({}/{} matched)",
            self.hg19_match_rate,
            self.hg19_lines - self.hg19_mismatches,
            self.hg19_lines,
            self.hg38_match_rate,
            self.hg38_lines - self.hg38_mismatches,
            self.hg38_lines
        )
    }
}

// ============================================================================
// Convenience Functions
// ============================================================================

/// Simplest way to check a VCF file against both references
///
/// Downloads references if needed, verifies against both, returns raw match rates.
///
/// # Example
/// ```rust,no_run
/// use check_build::detect_build;
///
/// let result = detect_build("sample.vcf").unwrap();
/// println!("hg19: {:.1}%", result.hg19_match_rate);
/// println!("hg38: {:.1}%", result.hg38_match_rate);
///
/// if let Some(better) = result.better_match() {
///     println!("Better match: {:?}", better);
/// }
/// ```
pub fn detect_build(vcf_path: impl Into<String>) -> Result<BuildResult, VerifyError> {
    let r = Verifier::new(vcf_path).silent().verify_both()?;
    Ok(BuildResult {
        hg19_match_rate: r.match_rate(Reference::Hg19),
        hg38_match_rate: r.match_rate(Reference::Hg38),
        hg19_lines: r.hg19_lines,
        hg38_lines: r.hg38_lines,
        hg19_mismatches: r.hg19_mismatches,
        hg38_mismatches: r.hg38_mismatches,
    })
}

/// Detect build from a list of positions (e.g. from DTC records)
///
/// This skips VCF parsing and works with arbitrary data.
pub fn detect_build_from_positions(positions: &[Variant]) -> Result<BuildResult, VerifyError> {
    let r = Verifier::from_variants(positions.to_vec())
        .silent()
        .verify_both()?;
    Ok(BuildResult {
        hg19_match_rate: r.match_rate(Reference::Hg19),
        hg38_match_rate: r.match_rate(Reference::Hg38),
        hg19_lines: r.hg19_lines,
        hg38_lines: r.hg38_lines,
        hg19_mismatches: r.hg19_mismatches,
        hg38_mismatches: r.hg38_mismatches,
    })
}

/// Detect build from positions using externally-managed reference files
///
/// This variant accepts custom paths to avoid re-downloading references.
/// If paths are provided, MD5 validation and auto-download are skipped.
///
/// # Example
/// ```rust,no_run
/// use check_build::{Variant, detect_build_from_positions_with_refs};
///
/// let variants = vec![
///     Variant { chrom: "1".into(), pos: 12345, ref_base: "A".into() },
/// ];
///
/// let result = detect_build_from_positions_with_refs(
///     &variants,
///     "/cache/hg19.fa",
///     "/cache/hg38.fa",
/// ).unwrap();
/// ```
pub fn detect_build_from_positions_with_refs(
    positions: &[Variant],
    hg19_path: impl Into<String>,
    hg38_path: impl Into<String>,
) -> Result<BuildResult, VerifyError> {
    let verifier = Verifier::from_variants(positions.to_vec())
        .silent()
        .with_reference_paths(hg19_path, hg38_path);

    let r = verifier.verify_both()?;
    Ok(BuildResult {
        hg19_match_rate: r.match_rate(Reference::Hg19),
        hg38_match_rate: r.match_rate(Reference::Hg38),
        hg19_lines: r.hg19_lines,
        hg38_lines: r.hg38_lines,
        hg19_mismatches: r.hg19_mismatches,
        hg38_mismatches: r.hg38_mismatches,
    })
}

/// Helper to detect if a VCF/variant set matches a specific reference path
///
/// Returns the match rate (0.0 to 100.0) against the provided reference.
pub fn detect_build_with_ref(
    vcf_path: impl Into<String>,
    ref_path: impl Into<String>,
) -> Result<f64, VerifyError> {
    let ref_path = ref_path.into();
    // Dummy reference enum for verify_single, but we override path
    let r = Verifier::new(vcf_path)
        .hg19_path(&ref_path) // Override hg19 path
        .silent()
        .no_download() // Don't download
        .verify_single(Reference::Hg19)?; // Check "Hg19" which now points to ref_path

    let (lines, mismatches) = r;
    if lines == 0 {
        return Ok(0.0);
    }
    Ok(((lines - mismatches) as f64 / lines as f64) * 100.0)
}

/// Error type for verification operations
#[derive(Debug)]
pub enum VerifyError {
    /// VCF file not found or invalid format
    InvalidVcf(String),
    /// Reference file not found
    ReferenceNotFound(String),
    /// I/O error
    Io(std::io::Error),
    /// Network/download error
    Download(String),
    /// Checksum mismatch
    ChecksumMismatch(String),
}

impl std::fmt::Display for VerifyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerifyError::InvalidVcf(msg) => write!(f, "Invalid VCF: {}", msg),
            VerifyError::ReferenceNotFound(path) => write!(f, "Reference not found: {}", path),
            VerifyError::Io(e) => write!(f, "I/O error: {}", e),
            VerifyError::Download(msg) => write!(f, "Download failed: {}", msg),
            VerifyError::ChecksumMismatch(msg) => write!(f, "Checksum mismatch: {}", msg),
        }
    }
}

impl std::error::Error for VerifyError {}

impl From<std::io::Error> for VerifyError {
    fn from(e: std::io::Error) -> Self {
        VerifyError::Io(e)
    }
}

// ============================================================================
// Verifier (Builder Pattern)
// ============================================================================

/// Builder for VCF verification with fluent API
///
/// # Example
/// ```rust,no_run
/// use check_build::Verifier;
///
/// let result = Verifier::new("sample.vcf")
///     .quiet()           // no progress bars
///     .silent()          // no mismatch output
///     .verify_both()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct Verifier {
    vcf_path: Option<String>,
    variants: Option<Vec<Variant>>,
    hg19_path: String,
    hg38_path: String,
    hg19_md5: Option<String>,
    hg38_md5: Option<String>,
    show_progress: bool,
    verbose: bool,
    auto_download: bool,
}

impl Verifier {
    /// Create a new verifier for the given VCF file
    pub fn new(vcf_path: impl Into<String>) -> Self {
        let (hg19, hg38) = Self::default_paths();
        Verifier {
            vcf_path: Some(vcf_path.into()),
            variants: None,
            hg19_path: hg19,
            hg38_path: hg38,
            hg19_md5: None, // Fetched dynamically from UCSC
            hg38_md5: None, // Fetched dynamically from UCSC
            show_progress: true,
            verbose: true,
            auto_download: true,
        }
    }

    /// Create a new verifier for a list of variants
    pub fn from_variants(variants: Vec<Variant>) -> Self {
        let (hg19, hg38) = Self::default_paths();
        Verifier {
            vcf_path: None,
            variants: Some(variants),
            hg19_path: hg19,
            hg38_path: hg38,
            hg19_md5: None, // Fetched dynamically from UCSC
            hg38_md5: None, // Fetched dynamically from UCSC
            show_progress: true,
            verbose: true,
            auto_download: true,
        }
    }

    fn default_paths() -> (String, String) {
        let cache_dir = dirs::cache_dir()
            .unwrap_or_else(|| std::env::current_dir().unwrap())
            .join("check_build");

        let hg19 = cache_dir
            .join(HG19_DEFAULT_PATH)
            .to_string_lossy()
            .into_owned();
        let hg38 = cache_dir
            .join(HG38_DEFAULT_PATH)
            .to_string_lossy()
            .into_owned();
        (hg19, hg38)
    }

    /// Set custom path for hg19 reference
    pub fn hg19_path(mut self, path: impl Into<String>) -> Self {
        self.hg19_path = path.into();
        self.hg19_md5 = None; // Disable checksum check for custom path
        self
    }

    /// Set custom path for hg38 reference
    pub fn hg38_path(mut self, path: impl Into<String>) -> Self {
        self.hg38_path = path.into();
        self.hg38_md5 = None; // Disable checksum check for custom path
        self
    }

    /// Disable progress bars
    pub fn quiet(mut self) -> Self {
        self.show_progress = false;
        self
    }

    /// Disable mismatch detail output (summary only)
    pub fn silent(mut self) -> Self {
        self.verbose = false;
        self
    }

    /// Disable automatic download of missing references
    pub fn no_download(mut self) -> Self {
        self.auto_download = false;
        self
    }

    /// Provide both reference paths and skip MD5 validation/downloading
    ///
    /// This is the preferred method when integrating check_build as a library
    /// and you've already cached the references elsewhere. It:
    /// - Sets custom paths for both hg19 and hg38
    /// - Disables MD5 checksum validation
    /// - Disables automatic downloading
    ///
    /// # Example
    /// ```rust,no_run
    /// use check_build::{Verifier, Variant};
    ///
    /// let variants = vec![
    ///     Variant { chrom: "1".into(), pos: 12345, ref_base: "A".into() },
    /// ];
    ///
    /// let result = Verifier::from_variants(variants)
    ///     .with_reference_paths("/cache/hg19.fa", "/cache/hg38.fa")
    ///     .silent()
    ///     .verify_both()
    ///     .unwrap();
    /// ```
    pub fn with_reference_paths(
        mut self,
        hg19_path: impl Into<String>,
        hg38_path: impl Into<String>,
    ) -> Self {
        self.hg19_path = hg19_path.into();
        self.hg38_path = hg38_path.into();
        self.hg19_md5 = None; // Skip MD5 validation for externally-managed references
        self.hg38_md5 = None;
        self.auto_download = false; // Trust caller's paths exist
        self
    }

    /// Verify against both hg19 and hg38 in parallel
    pub fn verify_both(&self) -> Result<VerificationResult, VerifyError> {
        self.validate_input()?;
        self.ensure_references()?;

        let split_dir = tempfile::tempdir()?;
        let contig_file_map = if let Some(ref path) = self.vcf_path {
            split_vcf_by_contig(path, &split_dir)?
        } else if let Some(ref variants) = self.variants {
            split_variants_by_contig(variants.iter().cloned(), &split_dir)?
        } else {
            return Err(VerifyError::InvalidVcf("No input provided".to_string()));
        };

        let contig_file_map = Arc::new(contig_file_map);

        let configs = [
            (&self.hg19_path, Reference::Hg19),
            (&self.hg38_path, Reference::Hg38),
        ];

        let results: Vec<(Reference, u64, u64)> = configs
            .par_iter()
            .map(|(path, reference)| {
                let (lines, mismatches) = verify_reference_streaming(
                    path,
                    &contig_file_map,
                    self.show_progress,
                    self.verbose,
                );
                (*reference, lines, mismatches)
            })
            .collect();

        let mut result = VerificationResult::default();
        for (reference, lines, mismatches) in results {
            match reference {
                Reference::Hg19 => {
                    result.hg19_lines = lines;
                    result.hg19_mismatches = mismatches;
                }
                Reference::Hg38 => {
                    result.hg38_lines = lines;
                    result.hg38_mismatches = mismatches;
                }
            }
        }

        Ok(result)
    }

    /// Verify against a single reference
    ///
    /// Returns `(lines_checked, mismatches)`
    pub fn verify_single(&self, reference: Reference) -> Result<(u64, u64), VerifyError> {
        self.validate_input()?;

        let (ref_path, md5) = match reference {
            Reference::Hg19 => (&self.hg19_path, self.hg19_md5.as_deref()),
            Reference::Hg38 => (&self.hg38_path, self.hg38_md5.as_deref()),
        };

        if self.auto_download {
            ensure_reference(ref_path, reference.url(), md5, self.show_progress)?;
        } else if !Path::new(ref_path).exists() {
            return Err(VerifyError::ReferenceNotFound(ref_path.clone()));
        }

        let split_dir = tempfile::tempdir()?;
        let contig_file_map = if let Some(ref path) = self.vcf_path {
            split_vcf_by_contig(path, &split_dir)?
        } else if let Some(ref variants) = self.variants {
            split_variants_by_contig(variants.iter().cloned(), &split_dir)?
        } else {
            return Err(VerifyError::InvalidVcf("No input provided".to_string()));
        };

        Ok(verify_reference_streaming(
            ref_path,
            &contig_file_map,
            self.show_progress,
            self.verbose,
        ))
    }

    fn validate_input(&self) -> Result<(), VerifyError> {
        if let Some(ref path) = self.vcf_path {
            if !path.ends_with(".vcf") {
                return Err(VerifyError::InvalidVcf(
                    "File must have .vcf extension (not .gz)".to_string(),
                ));
            }
            if !Path::new(path).exists() {
                return Err(VerifyError::InvalidVcf(format!("File not found: {}", path)));
            }
        } else if self.variants.is_none() {
            return Err(VerifyError::InvalidVcf(
                "No VCF path or variants provided".to_string(),
            ));
        }
        Ok(())
    }

    fn ensure_references(&self) -> Result<(), VerifyError> {
        if self.auto_download {
            // Fetch MD5 dynamically from UCSC if not provided
            let hg19_md5 = self.hg19_md5.clone().or_else(|| {
                fetch_md5_for_file(HG19_MD5_URL, HG19_DEFAULT_PATH, self.show_progress).ok()
            });
            let hg38_md5 = self.hg38_md5.clone().or_else(|| {
                fetch_md5_for_file(HG38_MD5_URL, HG38_DEFAULT_PATH, self.show_progress).ok()
            });

            ensure_reference(
                &self.hg19_path,
                HG19_URL,
                hg19_md5.as_deref(),
                self.show_progress,
            )?;
            ensure_reference(
                &self.hg38_path,
                HG38_URL,
                hg38_md5.as_deref(),
                self.show_progress,
            )?;
        } else {
            if !Path::new(&self.hg19_path).exists() {
                return Err(VerifyError::ReferenceNotFound(self.hg19_path.clone()));
            }
            if !Path::new(&self.hg38_path).exists() {
                return Err(VerifyError::ReferenceNotFound(self.hg38_path.clone()));
            }
        }
        Ok(())
    }
}

// ============================================================================
// Standalone Functions (for advanced users)
// ============================================================================

/// Ensure a reference file exists, downloading if necessary
pub fn ensure_reference(
    path: &str,
    url: &str,
    expected_md5: Option<&str>,
    show_progress: bool,
) -> Result<(), VerifyError> {
    if let Some(parent) = Path::new(path).parent() {
        std::fs::create_dir_all(parent)?;
    }

    if Path::new(path).exists() {
        if let Some(md5) = expected_md5 {
            if check_md5(path, md5)? {
                return Ok(());
            } else if show_progress {
                eprintln!("Checksum mismatch for {}, redownloading...", path);
            }
        } else {
            return Ok(());
        }
    }

    download_file(url, path, show_progress)?;

    if let Some(md5) = expected_md5 {
        if !check_md5(path, md5)? {
            return Err(VerifyError::ChecksumMismatch(format!(
                "Downloaded file {} does not match expected MD5 {}",
                path, md5
            )));
        }
    }

    Ok(())
}

fn check_md5(path: &str, expected: &str) -> Result<bool, VerifyError> {
    let mut file = File::open(path)?;
    let mut hasher = md5::Context::new();
    let mut buffer = [0; 8192];

    loop {
        let count = file.read(&mut buffer).map_err(VerifyError::Io)?;
        if count == 0 {
            break;
        }
        hasher.consume(&buffer[..count]);
    }

    let result = hasher.finalize();
    let result_str = format!("{:x}", result);
    Ok(result_str == expected)
}

/// Fetch MD5 checksum for a specific file from a UCSC md5sum.txt URL
fn fetch_md5_for_file(
    md5_url: &str,
    filename: &str,
    show_progress: bool,
) -> Result<String, VerifyError> {
    if show_progress {
        eprintln!("Fetching MD5 checksum from {}...", md5_url);
    }

    let client = Client::new();
    let response = client
        .get(md5_url)
        .send()
        .map_err(|e| VerifyError::Download(e.to_string()))?;

    if !response.status().is_success() {
        return Err(VerifyError::Download(format!(
            "Failed to fetch md5sum.txt: HTTP {}",
            response.status()
        )));
    }

    let body = response
        .text()
        .map_err(|e| VerifyError::Download(e.to_string()))?;

    // Parse md5sum.txt format: "checksum  filename"
    for line in body.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 2 && parts[1] == filename {
            if show_progress {
                eprintln!("Found MD5 for {}: {}", filename, parts[0]);
            }
            return Ok(parts[0].to_string());
        }
    }

    Err(VerifyError::Download(format!(
        "MD5 for {} not found in {}",
        filename, md5_url
    )))
}

/// Generate contig name candidates for flexible matching
///
/// Handles both "chr1" -> "1" and "1" -> "chr1" conversions
pub fn get_contig_candidates(contig: &str) -> Vec<String> {
    let mut candidates = Vec::with_capacity(2);
    candidates.push(contig.to_string());

    if let Some(stripped) = contig.strip_prefix("chr") {
        if !stripped.is_empty() {
            candidates.push(stripped.to_string());
        }
    } else {
        candidates.push(format!("chr{}", contig));
    }

    candidates
}

/// Compare byte slices ignoring ASCII case
#[inline]
pub fn equals_ignore_case(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.eq_ignore_ascii_case(y))
}

// ============================================================================
// Internal Implementation
// ============================================================================

fn download_file(url: &str, dest_path: &str, show_progress: bool) -> Result<(), VerifyError> {
    if show_progress {
        eprintln!("Downloading {} to {}...", url, dest_path);
    }

    let client = Client::new();
    let mut response = client
        .get(url)
        .send()
        .map_err(|e| VerifyError::Download(e.to_string()))?;

    if !response.status().is_success() {
        return Err(VerifyError::Download(format!("HTTP {}", response.status())));
    }

    let total_size = response.content_length();

    let pb = if show_progress {
        let pb = ProgressBar::new(total_size.unwrap_or(0));
        pb.set_draw_target(ProgressDrawTarget::stderr());
        pb.set_style(
            ProgressStyle::default_bar()
                .template("{msg} [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
                .expect("template")
                .progress_chars("=>-"),
        );
        pb.set_message(dest_path.to_string());
        Some(pb)
    } else {
        None
    };

    let out_file = File::create(dest_path)?;
    let mut writer = BufWriter::with_capacity(DOWNLOAD_BUFFER_SIZE, out_file);
    let mut downloaded = 0u64;
    let mut buffer = [0u8; DOWNLOAD_BUFFER_SIZE];

    loop {
        let n = response.read(&mut buffer).map_err(VerifyError::Io)?;
        if n == 0 {
            break;
        }
        writer.write_all(&buffer[..n])?;
        downloaded += n as u64;
        if let Some(ref pb) = pb {
            pb.set_position(downloaded);
        }
    }
    writer.flush()?;

    if let Some(pb) = pb {
        pb.finish_with_message(format!("Downloaded {}", dest_path));
    }

    Ok(())
}

/// Split VCF by contig into temporary files
pub fn split_vcf_by_contig(
    vcf_path: &str,
    split_dir: &TempDir,
) -> Result<HashMap<String, PathBuf>, VerifyError> {
    let f = File::open(vcf_path)?;
    let reader = BufReader::with_capacity(FASTA_READ_BUFFER_SIZE, f);

    let iter = reader.lines().filter_map(|l| l.ok()).filter_map(|line| {
        if line.starts_with('#') || line.trim().is_empty() {
            return None;
        }

        let mut parts = line.split('\t');
        let contig = parts.next()?;
        if contig.is_empty() {
            return None;
        }

        let pos_str = parts.next()?;
        let _id = parts.next();
        let ref_base = parts.next()?;

        let pos = pos_str.parse::<u64>().ok()?;

        Some(Variant {
            chrom: contig.to_string(),
            pos,
            ref_base: ref_base.to_string(),
        })
    });

    split_variants_by_contig(iter, split_dir)
}

fn split_variants_by_contig(
    variants: impl Iterator<Item = Variant>,
    split_dir: &TempDir,
) -> Result<HashMap<String, PathBuf>, VerifyError> {
    let mut handles: HashMap<String, BufWriter<File>> = HashMap::new();
    let mut file_paths: HashMap<String, PathBuf> = HashMap::new();

    for v in variants {
        let contig_owned = v.chrom;

        if !handles.contains_key(&contig_owned) {
            let contig_file = split_dir.path().join(format!("{}.tmp", contig_owned));
            let f = OpenOptions::new()
                .create(true)
                .append(true)
                .open(&contig_file)?;
            handles.insert(contig_owned.clone(), BufWriter::with_capacity(65536, f));
            file_paths.insert(contig_owned.clone(), contig_file);
        }

        if let Some(h) = handles.get_mut(&contig_owned) {
            // Write in a format compatible with verify_contig: CHROM POS ID REF
            // We use "." for ID.
            writeln!(h, "{}\t{}\t.\t{}", contig_owned, v.pos, v.ref_base)?;
        }
    }

    for (_, mut w) in handles {
        w.flush()?;
    }

    Ok(file_paths)
}

struct ContigState {
    current_contig: String,
    current_seq: Vec<u8>,
    lines_checked: u64,
    mismatches: u64,
}

impl ContigState {
    fn new() -> Self {
        ContigState {
            current_contig: String::new(),
            current_seq: Vec::with_capacity(EXPECTED_MAX_CONTIG_SIZE),
            lines_checked: 0,
            mismatches: 0,
        }
    }

    fn flush(&mut self, contig_file_map: &HashMap<String, PathBuf>, verbose: bool) {
        if self.current_contig.is_empty() {
            return;
        }
        let cnt = verify_contig(
            &self.current_contig,
            &self.current_seq,
            contig_file_map,
            &mut self.mismatches,
            verbose,
        );
        self.lines_checked += cnt;
        self.current_contig.clear();
        self.current_seq.clear();
    }
}

fn verify_reference_streaming(
    fasta_path: &str,
    contig_file_map: &HashMap<String, PathBuf>,
    show_progress: bool,
    verbose: bool,
) -> (u64, u64) {
    let meta = match std::fs::metadata(fasta_path) {
        Ok(m) => m,
        Err(_) => return (0, 0),
    };

    let pb = if show_progress {
        let pb = ProgressBar::new(meta.len());
        pb.set_draw_target(ProgressDrawTarget::stderr());
        pb.set_style(
            ProgressStyle::default_bar()
                .template(&format!(
                    "{} {{spinner}} [{{bar:40.cyan/blue}}] {{bytes}}/{{total_bytes}} ({{eta}})",
                    fasta_path
                ))
                .expect("template")
                .progress_chars("=>-"),
        );
        Some(pb)
    } else {
        None
    };

    let mut reader: Box<dyn BufRead> = match File::open(fasta_path) {
        Ok(mut f) => {
            // Check magic bytes to detect gzip even if extension doesn't match
            let mut magic = [0u8; 2];
            let is_gzip = if f.read_exact(&mut magic).is_ok() {
                magic == [0x1f, 0x8b]
            } else {
                false
            };
            // Seek back to start
            let _ = f.seek(std::io::SeekFrom::Start(0));

            if is_gzip {
                Box::new(BufReader::with_capacity(
                    FASTA_READ_BUFFER_SIZE,
                    GzDecoder::new(f),
                ))
            } else {
                Box::new(BufReader::with_capacity(FASTA_READ_BUFFER_SIZE, f))
            }
        }
        Err(_) => return (0, 0),
    };

    let mut chunk = vec![0u8; FASTA_READ_BUFFER_SIZE];
    let mut read_bytes = 0u64;
    let mut line_buf = Vec::<u8>::with_capacity(1024);
    let mut state = ContigState::new();

    while let Ok(n) = reader.read(&mut chunk) {
        if n == 0 {
            break;
        }
        read_bytes += n as u64;
        if let Some(ref pb) = pb {
            pb.set_position(read_bytes);
        }
        process_chunk(
            &mut state,
            &mut line_buf,
            &chunk[..n],
            contig_file_map,
            verbose,
        );
    }

    if !line_buf.is_empty() {
        process_line(&mut state, &mut line_buf, contig_file_map, verbose);
    }
    state.flush(contig_file_map, verbose);

    if let Some(pb) = pb {
        pb.finish_with_message(format!("Done {}", fasta_path));
    }

    (state.lines_checked, state.mismatches)
}

fn process_chunk(
    state: &mut ContigState,
    line_buf: &mut Vec<u8>,
    chunk: &[u8],
    contig_file_map: &HashMap<String, PathBuf>,
    verbose: bool,
) {
    let mut start = 0;
    while start < chunk.len() {
        match memchr(b'\n', &chunk[start..]) {
            Some(pos) => {
                let end = start + pos;
                let line_end = if end > start && chunk[end - 1] == b'\r' {
                    end - 1
                } else {
                    end
                };
                line_buf.extend_from_slice(&chunk[start..line_end]);
                process_line(state, line_buf, contig_file_map, verbose);
                line_buf.clear();
                start = end + 1;
            }
            None => {
                for &b in &chunk[start..] {
                    if b != b'\r' {
                        line_buf.push(b);
                    }
                }
                break;
            }
        }
    }
}

fn process_line(
    state: &mut ContigState,
    line_buf: &mut [u8],
    contig_file_map: &HashMap<String, PathBuf>,
    verbose: bool,
) {
    if line_buf.is_empty() {
        return;
    }
    if line_buf[0] == b'>' {
        state.flush(contig_file_map, verbose);
        let line_str = String::from_utf8_lossy(&line_buf[1..]);
        state.current_contig = line_str.split_whitespace().next().unwrap_or("").to_string();
    } else {
        for b in line_buf.iter_mut() {
            b.make_ascii_uppercase();
        }
        state.current_seq.extend_from_slice(line_buf);
    }
}

/// Verify VCF lines for a contig against reference sequence
pub fn verify_contig(
    contig: &str,
    seq: &[u8],
    contig_file_map: &HashMap<String, PathBuf>,
    mismatch_count: &mut u64,
    verbose: bool,
) -> u64 {
    let candidates = get_contig_candidates(contig);
    let file_path = candidates.iter().find_map(|c| contig_file_map.get(c));

    let contig_file = match file_path {
        Some(p) => p,
        None => return 0,
    };

    let f = match File::open(contig_file) {
        Ok(x) => x,
        Err(_) => return 0,
    };

    let mut lines_checked = 0u64;
    let reader = BufReader::with_capacity(65536, f);

    for line_res in reader.lines() {
        let line = match line_res {
            Ok(x) => x,
            Err(_) => break,
        };
        lines_checked += 1;

        let mut parts = line.split('\t');
        let _contig = parts.next();
        let pos_str = match parts.next() {
            Some(p) => p,
            None => continue,
        };
        let _id = parts.next();
        let ref_allele = match parts.next() {
            Some(r) => r,
            None => continue,
        };

        let pos_1based = match pos_str.parse::<u64>() {
            Ok(p) => p,
            Err(_) => continue,
        };
        let pos_0based = pos_1based.saturating_sub(1);
        let end_pos = pos_0based + ref_allele.len() as u64;

        if end_pos > seq.len() as u64 {
            if verbose {
                eprintln!(
                    "WARNING: Out-of-bounds: {}:{} ref_len={} seq_len={}",
                    contig,
                    pos_1based,
                    ref_allele.len(),
                    seq.len()
                );
            }
            continue;
        }

        let slice = &seq[pos_0based as usize..end_pos as usize];
        if !equals_ignore_case(slice, ref_allele.as_bytes()) {
            if verbose {
                eprintln!(
                    "Mismatch: {}:{} REF='{}' FASTA='{}'",
                    contig,
                    pos_str,
                    ref_allele,
                    String::from_utf8_lossy(slice)
                );
            }
            *mismatch_count += 1;
        }
    }

    lines_checked
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_equals_ignore_case() {
        assert!(equals_ignore_case(b"ACGT", b"ACGT"));
        assert!(equals_ignore_case(b"acgt", b"ACGT"));
        assert!(equals_ignore_case(b"AcGt", b"aCgT"));
        assert!(!equals_ignore_case(b"ACGT", b"ACG"));
        assert!(!equals_ignore_case(b"ACGT", b"ACGA"));
        assert!(equals_ignore_case(b"", b""));
    }

    #[test]
    fn test_get_contig_candidates() {
        let c = get_contig_candidates("chr1");
        assert!(c.contains(&"chr1".to_string()));
        assert!(c.contains(&"1".to_string()));
        assert!(!c.iter().any(|x| x.contains("chrchr")));

        let c = get_contig_candidates("1");
        assert!(c.contains(&"1".to_string()));
        assert!(c.contains(&"chr1".to_string()));
    }

    #[test]
    fn test_verification_result_likely_build() {
        let r1 = VerificationResult {
            hg19_lines: 100,
            hg19_mismatches: 0,
            hg38_lines: 100,
            hg38_mismatches: 50,
        };
        assert_eq!(r1.likely_build(), Some(Reference::Hg19));

        let r2 = VerificationResult {
            hg19_lines: 100,
            hg19_mismatches: 50,
            hg38_lines: 100,
            hg38_mismatches: 0,
        };
        assert_eq!(r2.likely_build(), Some(Reference::Hg38));

        let r3 = VerificationResult {
            hg19_lines: 100,
            hg19_mismatches: 0,
            hg38_lines: 100,
            hg38_mismatches: 0,
        };
        assert_eq!(r3.likely_build(), None);
    }

    #[test]
    fn test_vcf_split_and_verify_roundtrip() {
        use tempfile::tempdir;

        let test_dir = tempdir().unwrap();
        let vcf_path = test_dir.path().join("test.vcf");

        {
            let mut f = File::create(&vcf_path).unwrap();
            writeln!(f, "##fileformat=VCFv4.2").unwrap();
            writeln!(f, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO").unwrap();
            writeln!(f, "chr1\t100\t.\tA\tG\t.\t.\t.").unwrap();
            writeln!(f, "chr1\t200\t.\tCG\tTA\t.\t.\t.").unwrap();
            writeln!(f, "chr2\t50\t.\tT\tC\t.\t.\t.").unwrap();
        }

        let split_dir = tempdir().unwrap();
        let map = split_vcf_by_contig(vcf_path.to_str().unwrap(), &split_dir).unwrap();

        assert_eq!(map.len(), 2);
        assert!(map.contains_key("chr1"));
        assert!(map.contains_key("chr2"));

        // Test matching sequence
        let mut seq = vec![b'N'; 300];
        seq[99] = b'A';
        seq[199] = b'C';
        seq[200] = b'G';

        let mut m = 0;
        let lines = verify_contig("chr1", &seq, &map, &mut m, false);
        assert_eq!(lines, 2);
        assert_eq!(m, 0);

        // Test mismatch
        let mut bad = vec![b'N'; 300];
        bad[99] = b'T'; // wrong
        bad[199] = b'C';
        bad[200] = b'G';

        let mut m2 = 0;
        verify_contig("chr1", &bad, &map, &mut m2, false);
        assert_eq!(m2, 1);
    }
}