gtars-refget 0.12.0

Rust implementation of the refget standard for accessing reference sequences
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
//! FASTA export and BED region extraction for RefgetStore.
//!
//! Exports stream one sequence at a time: each record's stored bytes are read
//! once (from RAM, a local `.seq` file, or the remote store) and decoded in
//! chunks, so peak memory is one sequence's packed bytes plus one chunk. An
//! export never loads sequences into the store and never writes `.seq` files
//! into a remote store's cache.

use super::*;
use super::label::{invert, label_err, AliasIndex, LabelTemplate};
use super::readonly::ReadonlyRefgetStore;

use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

use anyhow::{anyhow, Context, Result};
use flate2::Compression;
use flate2::write::GzEncoder;
use flate2::read::MultiGzDecoder;
use gtars_core::utils::get_file_info;

use crate::digest::{
    AlphabetType, SequenceMetadata, decode_substring_from_bytes, lookup_alphabet, strip_sq_prefix,
};
use super::catalog::SeqRow;

/// Bases decoded per chunk when streaming a record.
pub(crate) const EXPORT_CHUNK_BASES: usize = 1 << 20;

/// Records between progress lines on stderr.
const PROGRESS_EVERY: usize = 1000;

// ============================================================================
// Public export types
// ============================================================================

/// Which records an export writes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExportSelection {
    /// One or more collections, optionally limited to some sequence names in each.
    Collections { digests: Vec<String>, names: Option<Vec<String>> },
    /// Specific sequences by digest. These records have no collection.
    SeqDigests(Vec<String>),
    /// Every collection, plus any sequence that is in no collection.
    All,
}

impl ExportSelection {
    /// Build a selection from binding-style arguments: exactly one of
    /// `collections`, `seq_digests` or `all`, and `names` only with collections.
    pub fn from_parts(
        collections: Option<Vec<String>>,
        names: Option<Vec<String>>,
        seq_digests: Option<Vec<String>>,
        all: bool,
    ) -> Result<Self> {
        if collections.is_some() as u8 + seq_digests.is_some() as u8 + all as u8 != 1 {
            return Err(label_err!("Set exactly one of collections, seq_digests or all"));
        }
        Ok(match (collections, seq_digests) {
            (Some(digests), _) => ExportSelection::Collections { digests, names },
            _ if names.is_some() => {
                return Err(label_err!("names only applies with collections"))
            }
            (_, Some(digests)) => ExportSelection::SeqDigests(digests),
            _ => ExportSelection::All,
        })
    }
}

/// Molecule filter: BLAST and similar tools need one molecule type per database.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Molecule {
    /// `Dna2bit`, `Dna3bit` and `DnaIupac` sequences.
    Dna,
    /// `Protein` sequences.
    Protein,
}

impl Molecule {
    /// Parse an optional `"dna"` / `"protein"` argument.
    pub fn from_opt(s: Option<&str>) -> Result<Option<Self>> {
        s.map(str::parse).transpose()
    }

    fn keeps(&self, alphabet: &AlphabetType) -> bool {
        match self {
            Molecule::Dna => matches!(
                alphabet,
                AlphabetType::Dna2bit | AlphabetType::Dna3bit | AlphabetType::DnaIupac
            ),
            Molecule::Protein => matches!(alphabet, AlphabetType::Protein),
        }
    }
}

impl std::str::FromStr for Molecule {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self> {
        match s.to_ascii_lowercase().as_str() {
            "dna" => Ok(Molecule::Dna),
            "protein" => Ok(Molecule::Protein),
            other => Err(label_err!("Invalid molecule '{}': expected 'dna' or 'protein'", other)),
        }
    }
}

/// How an export labels and formats its records.
#[derive(Debug, Clone)]
pub struct ExportOptions {
    /// Label template; default `{seq}`.
    pub label: LabelTemplate,
    /// Keep only sequences of this molecule type.
    pub molecule: Option<Molecule>,
    /// Bases per line, default 80; `0` writes each sequence on one line.
    pub line_width: usize,
}

impl Default for ExportOptions {
    fn default() -> Self {
        Self { label: LabelTemplate::default(), molecule: None, line_width: 80 }
    }
}

/// Counts reported by an export.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ExportSummary {
    /// Records written.
    pub n_records: usize,
    /// Bases written.
    pub n_bases: u64,
    /// Records whose label fell back to a digest (missing alias, or no collection).
    pub n_fallbacks: usize,
    /// Records skipped because the same label and sequence were already written.
    pub n_deduplicated: usize,
}

// ============================================================================
// Output and record writing
// ============================================================================

/// Open an export destination. `"-"` is stdout; a `.gz` path is gzipped.
pub(crate) fn open_output(path: &Path) -> Result<Box<dyn Write>> {
    if path == Path::new("-") {
        return Ok(Box::new(BufWriter::with_capacity(1 << 20, std::io::stdout().lock())));
    }
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent)?;
    }
    let file = File::create(path)
        .with_context(|| format!("Failed to create output file: {}", path.display()))?;
    Ok(if path.extension() == Some(OsStr::new("gz")) {
        Box::new(GzEncoder::new(BufWriter::new(file), Compression::default()))
    } else {
        Box::new(BufWriter::new(file))
    })
}

/// Write `bases` as lines of `line_width` (`0`: no wrapping, no newline).
/// Callers keep every chunk but the last a multiple of `line_width`.
fn write_lines(writer: &mut dyn Write, bases: &[u8], line_width: usize) -> Result<()> {
    if line_width == 0 {
        writer.write_all(bases)?;
    } else {
        for line in bases.chunks(line_width) {
            writer.write_all(line)?;
            writer.write_all(b"\n")?;
        }
    }
    Ok(())
}

/// Read until `buf` is full or the reader ends; return the bytes read.
fn read_full(reader: &mut impl std::io::Read, buf: &mut [u8]) -> Result<usize> {
    let mut filled = 0;
    while filled < buf.len() {
        match reader.read(&mut buf[filled..]) {
            Ok(0) => break,
            Ok(n) => filled += n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e.into()),
        }
    }
    Ok(filled)
}

/// Write one FASTA record, decoding the body in chunks of about `chunk_bases`.
///
/// `header` is the label, written as `>{header}`. `data` is the stored bytes
/// (packed, raw or zstd per `mode`). `line_width > 0` wraps the body;
/// `0` writes it on a single line.
pub(crate) fn write_fasta_record(
    writer: &mut dyn Write,
    header: &str,
    meta: &SequenceMetadata,
    data: &[u8],
    mode: StorageMode,
    line_width: usize,
    chunk_bases: usize,
) -> Result<()> {
    // A multiple of line_width, so line breaks never straddle a chunk.
    let chunk = if line_width == 0 {
        chunk_bases.max(1)
    } else {
        (chunk_bases / line_width).max(1) * line_width
    };

    writer.write_all(b">")?;
    writer.write_all(header.as_bytes())?;
    writer.write_all(b"\n")?;

    match mode {
        StorageMode::Encoded => {
            let alphabet = lookup_alphabet(&meta.alphabet);
            let mut start = 0;
            while start < meta.length {
                let end = (start + chunk).min(meta.length);
                let decoded = decode_substring_from_bytes(data, start, end, alphabet);
                write_lines(writer, &decoded, line_width)?;
                start = end;
            }
        }
        StorageMode::Raw => {
            for piece in data.chunks(chunk) {
                write_lines(writer, piece, line_width)?;
            }
        }
        StorageMode::Zstd => {
            let mut decoder = zstd::stream::read::Decoder::with_buffer(data)
                .context("Failed to open zstd sequence record")?;
            let mut buf = vec![0u8; chunk];
            loop {
                let n = read_full(&mut decoder, &mut buf)
                    .context("Failed to zstd-decompress sequence record")?;
                if n == 0 {
                    break;
                }
                write_lines(writer, &buf[..n], line_width)?;
                if n < chunk {
                    break;
                }
            }
        }
    }

    if line_width == 0 {
        writer.write_all(b"\n")?;
    }
    Ok(())
}

/// One record to write: its label and the sequence behind it.
struct PlannedRecord {
    label: String,
    row: SeqRow,
}

/// A record before labeling: the sequence plus how it was reached.
struct Candidate<'a> {
    row: SeqRow,
    /// `(collection digest, sequence name)` when reached through a collection.
    collection: Option<(String, &'a str)>,
}

fn source_of(collection: &Option<(String, &str)>) -> String {
    match collection {
        Some((col, _)) => format!("collection {}", col),
        None => "the sequence list".to_string(),
    }
}

// ============================================================================
// Shared per-region substring retrieval
// ============================================================================

/// Retrieve the substring for a single region, shared by the file-based and
/// vectors-based iterators.
///
/// Mutates the caller-owned `previous_parsed_chr` / `current_seq_digest` cache
/// so the consecutive-same-chrom optimization works across either path.
/// `region_label` (e.g. `"Line 5"` or `"Region 5"`) is interpolated into error
/// messages.
#[allow(clippy::too_many_arguments)]
fn retrieve_substring_for_region<K: AsRef<[u8]>>(
    store: &ReadonlyRefgetStore,
    collection_digest: &K,
    parsed_chr: String,
    parsed_start: i64,
    parsed_end: i64,
    previous_parsed_chr: &mut String,
    current_seq_digest: &mut String,
    region_label: &str,
) -> Result<RetrievedSequence> {
    if parsed_start < 0 || parsed_end < 0 {
        return Err(anyhow!(
            "{} has invalid start or end coordinates: start={}, end={}",
            region_label,
            parsed_start,
            parsed_end
        ));
    }

    if *previous_parsed_chr != parsed_chr {
        *previous_parsed_chr = parsed_chr.clone();

        let result = store
            .get_sequence_by_name(collection_digest, &parsed_chr)
            .map_err(|e| {
                anyhow!(
                    "{}: sequence '{}' not found in collection '{}': {}",
                    region_label,
                    parsed_chr,
                    String::from_utf8_lossy(collection_digest.as_ref()),
                    e
                )
            })?;

        *current_seq_digest = result.metadata().sha512t24u.clone();
    }

    let retrieved_substring = store
        .get_substring(&*current_seq_digest, parsed_start as usize, parsed_end as usize)
        .map_err(|e| {
            anyhow!(
                "{}: failed to get substring for digest '{}' from {} to {}: {}",
                region_label,
                current_seq_digest,
                parsed_start,
                parsed_end,
                e
            )
        })?;

    Ok(RetrievedSequence {
        sequence: retrieved_substring,
        chrom_name: parsed_chr,
        start: parsed_start as u32,
        end: parsed_end as u32,
    })
}

// ============================================================================
// SubstringsFromRegions Iterator impl
// ============================================================================

impl<K> Iterator for SubstringsFromRegions<'_, K>
where
    K: AsRef<[u8]>,
{
    type Item = Result<RetrievedSequence, anyhow::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        use gtars_core::utils::parse_bedlike_file;

        let mut line_string = String::new();

        let num_bytes = self.reader.read_line(&mut line_string);
        match num_bytes {
            Ok(bytes) => {
                if bytes == 0 {
                    return None;
                }
            }
            Err(err) => return Some(Err(err.into())),
        };

        self.line_num += 1;

        let (parsed_chr, parsed_start, parsed_end) = match parse_bedlike_file(line_string.trim()) {
            Some(coords) => coords,
            None => {
                let err_str = format!(
                    "Error reading line {} because it could not be parsed as a BED-like entry: '{}'",
                    self.line_num + 1,
                    line_string
                );
                return Some(Err(anyhow!(err_str)));
            }
        };

        Some(retrieve_substring_for_region(
            self.store,
            &self.collection_digest,
            parsed_chr,
            parsed_start as i64,
            parsed_end as i64,
            &mut self.previous_parsed_chr,
            &mut self.current_seq_digest,
            &format!("Line {}", self.line_num + 1),
        ))
    }
}

// ============================================================================
// SubstringsFromRegionVectors Iterator impl
// ============================================================================

impl<K> Iterator for SubstringsFromRegionVectors<'_, K>
where
    K: AsRef<[u8]>,
{
    type Item = Result<RetrievedSequence, anyhow::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.chroms.len() {
            return None;
        }
        let i = self.index;
        self.index += 1;

        let parsed_chr = self.chroms[i].clone();
        let parsed_start = self.starts[i] as i64;
        let parsed_end = self.ends[i] as i64;

        Some(retrieve_substring_for_region(
            self.store,
            &self.collection_digest,
            parsed_chr,
            parsed_start,
            parsed_end,
            &mut self.previous_parsed_chr,
            &mut self.current_seq_digest,
            &format!("Region {}", i + 1),
        ))
    }
}

// ============================================================================
// ReadonlyRefgetStore export methods
// ============================================================================

impl ReadonlyRefgetStore {
    /// Get an iterator over substrings defined by BED file regions.
    pub fn substrings_from_regions<'a, K: AsRef<[u8]>>(
        &'a self,
        collection_digest: K,
        bed_file_path: &str,
    ) -> Result<SubstringsFromRegions<'a, K>> {
        let path = Path::new(bed_file_path);
        let file_info = get_file_info(path);
        let is_gzipped = file_info.is_gzipped;

        let opened_bed_file = File::open(path)?;

        let reader: Box<dyn std::io::Read> = match is_gzipped {
            true => Box::new(MultiGzDecoder::new(std::io::BufReader::new(opened_bed_file))),
            false => Box::new(opened_bed_file),
        };
        let reader = std::io::BufReader::new(reader);

        Ok(SubstringsFromRegions {
            store: self,
            reader,
            collection_digest,
            previous_parsed_chr: String::new(),
            current_seq_digest: String::new(),
            line_num: 0,
        })
    }

    /// Get an iterator over substrings defined by in-memory region vectors.
    ///
    /// `chroms`, `starts`, and `ends` are parallel slices; element `i` defines
    /// region `chroms[i]:starts[i]-ends[i]`. Yields the same `RetrievedSequence`
    /// results as `substrings_from_regions` without any temp-file round-trip.
    pub fn substrings_from_region_vectors<'a, K, S>(
        &'a self,
        collection_digest: K,
        chroms: &[S],
        starts: &[u32],
        ends: &[u32],
    ) -> Result<SubstringsFromRegionVectors<'a, K>>
    where
        K: AsRef<[u8]>,
        S: AsRef<str>,
    {
        if chroms.len() != starts.len() || chroms.len() != ends.len() {
            return Err(anyhow!(
                "Mismatched region vector lengths: chroms={}, starts={}, ends={}",
                chroms.len(),
                starts.len(),
                ends.len()
            ));
        }

        Ok(SubstringsFromRegionVectors {
            store: self,
            collection_digest,
            chroms: chroms.iter().map(|c| c.as_ref().to_string()).collect(),
            starts: starts.to_vec(),
            ends: ends.to_vec(),
            index: 0,
            previous_parsed_chr: String::new(),
            current_seq_digest: String::new(),
        })
    }

    /// Digest -> alias maps for every sequence and collection namespace
    /// `label` uses, after checking each namespace exists in this store.
    pub(crate) fn label_alias_maps(&self, label: &LabelTemplate) -> Result<(AliasIndex, AliasIndex)> {
        Ok((
            self.label_aliases(label, AliasKind::Sequence)?,
            self.label_aliases(label, AliasKind::Collection)?,
        ))
    }

    /// [`Self::label_alias_maps`] for the namespaces of one alias kind.
    fn label_aliases(&self, label: &LabelTemplate, kind: AliasKind) -> Result<AliasIndex> {
        let what = match kind {
            AliasKind::Sequence => "sequence",
            AliasKind::Collection => "collection",
        };
        let available = self.aliases.namespaces_for(kind);
        let mut out = AliasIndex::new();
        for ns in label.namespaces(kind) {
            if !available.contains(&ns) {
                return Err(label_err!(
                    "Unknown {}-alias namespace '{}' in label '{}'. This store's {}-alias namespaces: {}",
                    what,
                    ns,
                    label,
                    what,
                    list_or_none(&available)
                ));
            }
            let map = invert(self.aliases.namespace_map(kind, &ns));
            out.insert(ns, map);
        }
        Ok(out)
    }

    /// Export sequences from BED file regions to a FASTA file.
    ///
    /// Writes one record per BED line, each on a single line, labeled by
    /// `label` with `:start-end` appended (as samtools does). Labels repeat
    /// when regions repeat; no uniqueness rule applies.
    pub fn export_fasta_from_regions<K: AsRef<[u8]>>(
        &self,
        collection_digest: K,
        bed_file_path: &str,
        output_file_path: &str,
        label: &LabelTemplate,
    ) -> Result<ExportSummary> {
        let coll = self.loaded_coll_row(collection_digest.as_ref())?;
        let collection_str = self.catalog.coll_meta(coll).digest.clone();
        let maps = self.label_alias_maps(label)?;

        // Label each name once, from the member the region lookup resolves the
        // name to (`member_by_name`), so a repeated name labels the same
        // sequence whose bases are written.
        let mut name_labels: HashMap<&str, (String, bool)> = HashMap::new();
        for m in self.catalog.members(coll) {
            if name_labels.contains_key(m.name()) {
                continue;
            }
            let member = self.catalog.member_by_name(coll, m.name()).unwrap_or(m);
            let sha = member.seq().sha512t24u();
            let rendered =
                label.render(sha.as_str(), Some((&collection_str, m.name())), &maps.0, &maps.1);
            check_label_whitespace(&rendered.0)?;
            name_labels.insert(m.name(), rendered);
        }

        let seq_iter = self.substrings_from_regions(&collection_digest, bed_file_path)?;
        let mut writer = open_output(Path::new(output_file_path))?;
        let mut summary = ExportSummary::default();

        for rs in seq_iter {
            let rs = rs?;
            let (name_label, fallback) = name_labels
                .get(rs.chrom_name.as_str())
                .ok_or_else(|| anyhow!("Sequence '{}' not found in collection", rs.chrom_name))?;
            writeln!(writer, ">{}:{}-{}", name_label, rs.start, rs.end)?;
            writer.write_all(rs.sequence.as_bytes())?;
            writer.write_all(b"\n")?;
            summary.n_records += 1;
            summary.n_bases += rs.sequence.len() as u64;
            summary.n_fallbacks += *fallback as usize;
        }

        writer.flush()?;
        Ok(summary)
    }

    /// Export sequences to a FASTA file, or to stdout when `output_path` is `"-"`.
    ///
    /// `selection` chooses which records to write; `opts.label` chooses how
    /// each is labeled, the same way whatever the selection. The whole
    /// `(label, sequence)` list is planned from metadata before any output is
    /// written, so label errors never leave half a file. A repeated label for
    /// the same sequence is written once (counted in `n_deduplicated`); a
    /// repeated label for different sequences is an error.
    ///
    /// Record order: collections in the order given (digest order for `All`),
    /// each in its own order; then, for `All`, sequences in no collection, in
    /// digest order. When the label uses no collection field (`{seq}`,
    /// `{seq:NS}`), `All` lists each sequence once in digest order, without
    /// reading any collection.
    ///
    /// Exports stream one sequence at a time and leave the store's loaded
    /// state unchanged. Collections named by `selection` (all of them for
    /// `All` with a collection field) must be loaded; [`RefgetStore::export_fasta`]
    /// loads them.
    pub fn export_fasta<P: AsRef<Path>>(
        &self,
        selection: &ExportSelection,
        output_path: P,
        opts: &ExportOptions,
    ) -> Result<ExportSummary> {
        let line_width = opts.line_width;
        let maps = self.label_alias_maps(&opts.label)?;
        let candidates = self.export_candidates(selection, &opts.label)?;

        // Plan: label every record, apply the uniqueness rule.
        let mut summary = ExportSummary::default();
        let mut seen: HashMap<String, (SeqRow, String)> = HashMap::new();
        let mut plan: Vec<PlannedRecord> = Vec::new();
        for c in candidates {
            let view = self.catalog.seq(c.row);
            if let Some(m) = opts.molecule {
                if !m.keeps(&view.alphabet()) {
                    continue;
                }
            }
            let sha = view.sha512t24u();
            let coll = c.collection.as_ref().map(|(col, name)| (col.as_str(), *name));
            let (label, fallback) = opts.label.render(sha.as_str(), coll, &maps.0, &maps.1);
            check_label_whitespace(&label)?;
            match seen.get(&label) {
                Some((row, _)) if *row == c.row => {
                    summary.n_deduplicated += 1;
                    continue;
                }
                Some((row, first_source)) => {
                    return Err(label_err!(
                        "Label '{}' would name two different sequences: {} from {} and {} from {}. \
                         Add {{col:NS}} or {{col}} to the label (for example '{{col}}/{{name}}') to make labels unique.",
                        label,
                        self.catalog.seq(*row).sha512t24u(),
                        first_source,
                        sha,
                        source_of(&c.collection)
                    ));
                }
                None => {}
            }
            summary.n_fallbacks += fallback as usize;
            seen.insert(label.clone(), (c.row, source_of(&c.collection)));
            plan.push(PlannedRecord { label, row: c.row });
        }
        drop(seen);

        // Write: stream each record's bytes.
        let mut writer = open_output(output_path.as_ref())?;
        let total = plan.len();
        for (i, rec) in plan.iter().enumerate() {
            let meta = self.catalog.seq(rec.row).to_metadata();
            let bytes = self.read_stored_bytes(rec.row, false)?;
            write_fasta_record(
                &mut *writer,
                &rec.label,
                &meta,
                &bytes[..],
                self.mode,
                line_width,
                EXPORT_CHUNK_BASES,
            )?;
            summary.n_records += 1;
            summary.n_bases += meta.length as u64;
            if !self.quiet && ((i + 1) % PROGRESS_EVERY == 0 || i + 1 == total) {
                eprintln!(
                    "exported {}/{} records ({:.2} GB)",
                    i + 1,
                    total,
                    summary.n_bases as f64 / 1e9
                );
            }
        }
        writer.flush()?;
        Ok(summary)
    }

    /// Every record a selection reaches, in output order, before labeling.
    fn export_candidates(
        &self,
        selection: &ExportSelection,
        label: &LabelTemplate,
    ) -> Result<Vec<Candidate<'_>>> {
        let mut out: Vec<Candidate<'_>> = Vec::new();

        match selection {
            ExportSelection::Collections { digests, names } => {
                if digests.is_empty() {
                    return Err(anyhow!("No collections selected for export"));
                }
                for digest in digests {
                    self.collection_candidates(digest, names.as_deref(), &mut out)?;
                }
            }
            ExportSelection::SeqDigests(digests) => {
                for d in digests {
                    let row = self
                        .catalog
                        .resolve(strip_sq_prefix(d))
                        .ok_or_else(|| anyhow!("Sequence record not found for digest: {}", d))?;
                    out.push(Candidate { row, collection: None });
                }
            }
            ExportSelection::All => {
                let mut in_collection: HashSet<SeqRow> = HashSet::new();
                if label.needs_collection() {
                    let mut coll_digests: Vec<String> = self
                        .catalog
                        .coll_rows()
                        .map(|c| self.catalog.coll_meta(c).digest.clone())
                        .collect();
                    coll_digests.sort();
                    for digest in &coll_digests {
                        let start = out.len();
                        self.collection_candidates(digest, None, &mut out)?;
                        in_collection.extend(out[start..].iter().map(|c| c.row));
                    }
                }
                let mut rest: Vec<(crate::digest::Digest32, SeqRow)> = self
                    .catalog
                    .seq_rows()
                    .filter(|r| !in_collection.contains(r))
                    .map(|r| (self.catalog.seq(r).sha512t24u(), r))
                    .collect();
                rest.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
                for (_, row) in rest {
                    out.push(Candidate { row, collection: None });
                }
            }
        }
        Ok(out)
    }

    /// Append one collection's records (optionally only `names`) to `out`.
    fn collection_candidates<'a>(
        &'a self,
        digest: &str,
        names: Option<&[String]>,
        out: &mut Vec<Candidate<'a>>,
    ) -> Result<()> {
        let coll = self.loaded_coll_row(digest)?;
        let digest_str = self.catalog.coll_meta(coll).digest.clone();
        let wanted: Option<HashSet<&str>> = names.map(|ns| ns.iter().map(String::as_str).collect());
        if let Some(names) = names {
            let present: HashSet<&str> = self.catalog.members(coll).map(|m| m.name()).collect();
            if let Some(n) = names.iter().find(|n| !present.contains(n.as_str())) {
                return Err(anyhow!("Sequence '{}' not found in collection {}", n, digest_str));
            }
        }
        for m in self.catalog.members(coll) {
            if wanted.as_ref().is_some_and(|w| !w.contains(m.name())) {
                continue;
            }
            out.push(Candidate {
                row: m.seq_row(),
                collection: Some((digest_str.clone(), m.name())),
            });
        }
        Ok(())
    }
}

fn list_or_none(items: &[String]) -> String {
    if items.is_empty() {
        "(none)".to_string()
    } else {
        items.join(", ")
    }
}

fn check_label_whitespace(label: &str) -> Result<()> {
    if label.is_empty() {
        return Err(label_err!("A record's label is empty; FASTA IDs need at least one character"));
    }
    if label.chars().any(char::is_whitespace) {
        return Err(label_err!(
            "Label '{}' contains whitespace; FASTA IDs end at the first space. Change the label template or the alias.",
            label
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::store::{ExportOptions, ExportSelection, FastaImportOptions, LabelTemplate, RefgetStore};
    use std::io::Write;

    fn coll(digest: &str) -> ExportSelection {
        ExportSelection::Collections { digests: vec![digest.to_string()], names: None }
    }

    fn name_opts(line_width: usize) -> ExportOptions {
        ExportOptions {
            label: LabelTemplate::parse("{name}").unwrap(),
            molecule: None,
            line_width,
        }
    }
    use tempfile::{NamedTempFile, TempDir};

    /// Build a small in-memory store from a temp FASTA and return it plus the
    /// digest of the single collection created.
    fn build_store() -> (RefgetStore, String) {
        let mut fasta = NamedTempFile::new().expect("create temp fasta");
        // A sequence longer than 80 bases so the wrapped export spans >1 line.
        writeln!(fasta, ">seq1").unwrap();
        writeln!(fasta, "{}", "ACGT".repeat(30)).unwrap(); // 120 bases
        writeln!(fasta, ">seq2").unwrap();
        writeln!(fasta, "TTGGCCAA").unwrap();
        fasta.flush().unwrap();

        let mut store = RefgetStore::in_memory();
        store
            .add_sequence_collection_from_fasta(fasta.path(), FastaImportOptions::new())
            .expect("import fasta");

        let collections = store.list_collections(0, usize::MAX, &[]).unwrap();
        let digest = collections.results[0].digest.clone();
        (store, digest)
    }

    /// Two single-record FASTAs with byte-identical sequences but different
    /// headers: `>chr1 ucsc desc` and `>1 flybase desc`. Mirrors the UCSC vs
    /// FlyBase situation from issue #270.
    fn shared_sequence_fastas() -> (NamedTempFile, NamedTempFile) {
        let seq = "ACGT".repeat(10);
        let mut a = NamedTempFile::new().expect("create temp fasta A");
        writeln!(a, ">chr1 ucsc desc").unwrap();
        writeln!(a, "{}", seq).unwrap();
        a.flush().unwrap();

        let mut b = NamedTempFile::new().expect("create temp fasta B");
        writeln!(b, ">1 flybase desc").unwrap();
        writeln!(b, "{}", seq).unwrap();
        b.flush().unwrap();
        (a, b)
    }

    /// Import `first` then `second` into `store`; return their collection digests.
    fn import_pair(store: &mut RefgetStore, first: &NamedTempFile, second: &NamedTempFile) -> (String, String) {
        let (meta_first, _) = store
            .add_sequence_collection_from_fasta(first.path(), FastaImportOptions::new())
            .expect("import first fasta");
        let (meta_second, _) = store
            .add_sequence_collection_from_fasta(second.path(), FastaImportOptions::new())
            .expect("import second fasta");
        (meta_first.digest, meta_second.digest)
    }

    /// Export a collection unwrapped and return the headers in order.
    fn export_headers(store: &crate::store::ReadonlyRefgetStore, digest: &str, dir: &TempDir) -> Vec<String> {
        let out = dir.path().join(format!("{}.fa", digest));
        store
            .export_fasta(&coll(digest), &out, &name_opts(0))
            .expect("export collection");
        let content = std::fs::read_to_string(&out).unwrap();
        records(&content).into_iter().map(|(h, _)| h).collect()
    }

    /// Split a FASTA into (header, body-lines) pairs.
    fn records(fasta: &str) -> Vec<(String, Vec<String>)> {
        let mut out: Vec<(String, Vec<String>)> = Vec::new();
        for line in fasta.lines() {
            if let Some(header) = line.strip_prefix('>') {
                out.push((header.to_string(), Vec::new()));
            } else if let Some(last) = out.last_mut() {
                last.1.push(line.to_string());
            }
        }
        out
    }

    #[test]
    fn export_unwrapped_puts_each_sequence_on_one_line() {
        let (store, digest) = build_store();
        let readonly = store.into_readonly();

        let dir = TempDir::new().unwrap();
        let out = dir.path().join("unwrapped.fa");
        readonly
            .export_fasta(&coll(&digest), &out, &name_opts(0))
            .expect("export unwrapped");

        let content = std::fs::read_to_string(&out).unwrap();
        let recs = records(&content);
        assert_eq!(recs.len(), 2, "expected two records");
        for (header, body) in &recs {
            assert_eq!(
                body.len(),
                1,
                "record '{}' should have exactly one body line when unwrapped, got {:?}",
                header,
                body
            );
        }
        // seq1 body is the full 120 bases on a single line.
        assert_eq!(recs[0].1[0].len(), 120);
    }

    #[test]
    fn export_wrapped_at_80_splits_long_sequences() {
        let (store, digest) = build_store();
        let readonly = store.into_readonly();

        let dir = TempDir::new().unwrap();
        let out = dir.path().join("wrapped.fa");
        readonly
            .export_fasta(&coll(&digest), &out, &name_opts(80))
            .expect("export wrapped");

        let content = std::fs::read_to_string(&out).unwrap();
        let recs = records(&content);
        // seq1 (120 bases) wraps to two lines at width 80; seq2 (8 bases) stays one.
        assert_eq!(recs[0].1.len(), 2, "120-base seq should wrap to 2 lines");
        assert_eq!(recs[0].1[0].len(), 80);
        assert_eq!(recs[0].1[1].len(), 40);
        assert_eq!(recs[1].1.len(), 1);
    }

    #[test]
    fn shared_sequence_exports_with_each_collections_own_name() {
        let (fasta_a, fasta_b) = shared_sequence_fastas();

        // Both import orders: the first-imported label must never leak into
        // the other collection's export.
        for swap in [false, true] {
            let mut store = RefgetStore::in_memory();
            let (digest_a, digest_b) = if swap {
                let (b, a) = import_pair(&mut store, &fasta_b, &fasta_a);
                (a, b)
            } else {
                import_pair(&mut store, &fasta_a, &fasta_b)
            };
            let readonly = store.into_readonly();
            let dir = TempDir::new().unwrap();

            assert_eq!(
                export_headers(&readonly, &digest_a, &dir),
                vec!["chr1".to_string()],
                "swap={}",
                swap
            );
            assert_eq!(
                export_headers(&readonly, &digest_b, &dir),
                vec!["1".to_string()],
                "swap={}",
                swap
            );
        }
    }

    #[test]
    fn get_collection_returns_per_collection_description() {
        let (fasta_a, fasta_b) = shared_sequence_fastas();
        let mut store = RefgetStore::in_memory();
        let (digest_a, digest_b) = import_pair(&mut store, &fasta_a, &fasta_b);
        let readonly = store.into_readonly();

        let coll_b = readonly.get_collection(&digest_b).expect("get collection B");
        assert_eq!(coll_b.sequences.len(), 1);
        assert_eq!(coll_b.sequences[0].metadata().name, "1");
        assert_eq!(
            coll_b.sequences[0].metadata().description.as_deref(),
            Some("flybase desc")
        );

        let coll_a = readonly.get_collection(&digest_a).expect("get collection A");
        assert_eq!(coll_a.sequences[0].metadata().name, "chr1");
        assert_eq!(
            coll_a.sequences[0].metadata().description.as_deref(),
            Some("ucsc desc")
        );
    }

    #[test]
    fn shared_sequence_disk_roundtrip_exports_own_name() {
        let (fasta_a, fasta_b) = shared_sequence_fastas();
        let store_dir = TempDir::new().unwrap();

        let (digest_a, digest_b) = {
            let mut store = RefgetStore::on_disk(store_dir.path()).expect("create disk store");
            import_pair(&mut store, &fasta_a, &fasta_b)
        };

        // Reopen so collection stubs come from collections/<digest>.rgsi via
        // ensure_collection_loaded, not from the import-time in-memory records.
        let mut store = RefgetStore::open_local(store_dir.path()).expect("reopen store");
        store.load_collection(&digest_b).expect("load collection B");
        store.load_collection(&digest_a).expect("load collection A");
        store.load_all_sequences().expect("load sequences");
        let readonly = store.into_readonly();

        let dir = TempDir::new().unwrap();
        assert_eq!(
            export_headers(&readonly, &digest_b, &dir),
            vec!["1".to_string()]
        );
        assert_eq!(
            export_headers(&readonly, &digest_a, &dir),
            vec!["chr1".to_string()]
        );

        let coll_b = readonly.get_collection(&digest_b).unwrap();
        assert_eq!(
            coll_b.sequences[0].metadata().description.as_deref(),
            Some("flybase desc")
        );
    }

    #[test]
    fn get_sequence_by_name_returns_per_collection_metadata() {
        let (fasta_a, fasta_b) = shared_sequence_fastas();

        // Both import orders: the first-imported label must never leak into
        // the other collection's get_sequence_by_name() result.
        for swap in [false, true] {
            let mut store = RefgetStore::in_memory();
            let (digest_a, digest_b) = if swap {
                let (b, a) = import_pair(&mut store, &fasta_b, &fasta_a);
                (a, b)
            } else {
                import_pair(&mut store, &fasta_a, &fasta_b)
            };
            let readonly = store.into_readonly();

            let rec_b = readonly
                .get_sequence_by_name(&digest_b, "1")
                .expect("get sequence '1' from collection B");
            assert_eq!(rec_b.metadata().name, "1", "swap={}", swap);
            assert_eq!(
                rec_b.metadata().description.as_deref(),
                Some("flybase desc"),
                "swap={}",
                swap
            );

            let rec_a = readonly
                .get_sequence_by_name(&digest_a, "chr1")
                .expect("get sequence 'chr1' from collection A");
            assert_eq!(rec_a.metadata().name, "chr1", "swap={}", swap);
            assert_eq!(
                rec_a.metadata().description.as_deref(),
                Some("ucsc desc"),
                "swap={}",
                swap
            );

            // Same underlying bytes, shared across both collections.
            assert_eq!(
                rec_a.metadata().sha512t24u,
                rec_b.metadata().sha512t24u,
                "swap={}",
                swap
            );

            // Names do not leak across collections.
            assert!(
                readonly.get_sequence_by_name(&digest_b, "chr1").is_err(),
                "swap={}",
                swap
            );
        }
    }

    #[test]
    fn get_sequence_by_name_disk_roundtrip() {
        let (fasta_a, fasta_b) = shared_sequence_fastas();
        let store_dir = TempDir::new().unwrap();

        let (digest_a, digest_b) = {
            let mut store = RefgetStore::on_disk(store_dir.path()).expect("create disk store");
            import_pair(&mut store, &fasta_a, &fasta_b)
        };

        // Reopen so collection stubs come from collections/<digest>.rgsi via
        // ensure_collection_loaded, not from the import-time in-memory records.
        let mut store = RefgetStore::open_local(store_dir.path()).expect("reopen store");
        store.load_collection(&digest_b).expect("load collection B");
        store.load_collection(&digest_a).expect("load collection A");
        store.load_all_sequences().expect("load sequences");
        let readonly = store.into_readonly();

        let rec_b = readonly
            .get_sequence_by_name(&digest_b, "1")
            .expect("get sequence '1' from collection B");
        assert_eq!(rec_b.metadata().name, "1");
        assert_eq!(rec_b.metadata().description.as_deref(), Some("flybase desc"));
        assert!(rec_b.is_loaded());
        assert_eq!(rec_b.decode().unwrap(), "ACGT".repeat(10));

        let rec_a = readonly
            .get_sequence_by_name(&digest_a, "chr1")
            .expect("get sequence 'chr1' from collection A");
        assert_eq!(rec_a.metadata().name, "chr1");
        assert_eq!(rec_a.metadata().description.as_deref(), Some("ucsc desc"));
        assert!(rec_a.is_loaded());
        assert_eq!(rec_a.decode().unwrap(), "ACGT".repeat(10));
    }
}