fastars 0.1.0

Ultra-fast QC and trimming for short and long reads
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
//! Adapter trimming.
//!
//! This module provides adapter detection and removal from read sequences.
//! Supports both known adapter databases and automatic adapter detection
//! for paired-end reads.
//!
//! # Optimizations
//! - Kmer-based indexing for O(n) average case adapter detection
//! - Overlap-based detection for paired-end reads (see overlap module)

use rustc_hash::FxHashMap;
use super::TrimResult;

// ============================================================================
// Kmer Index for Fast Adapter Detection
// ============================================================================

/// Size of k-mer for adapter indexing (8bp gives good balance of specificity and speed).
const KMER_SIZE: usize = 8;

/// Pre-computed k-mer index for fast adapter detection.
/// Maps k-mer hash to positions in the adapter where it occurs.
#[derive(Debug, Clone)]
pub struct AdapterKmerIndex {
    /// K-mer to positions mapping.
    kmer_positions: FxHashMap<u64, Vec<usize>>,
    /// Original adapter sequence.
    adapter: Vec<u8>,
    /// Minimum match length.
    min_match_len: usize,
}

impl AdapterKmerIndex {
    /// Build a k-mer index for the given adapter sequence.
    pub fn new(adapter: &[u8], min_match_len: usize) -> Self {
        let mut kmer_positions: FxHashMap<u64, Vec<usize>> = FxHashMap::default();

        if adapter.len() >= KMER_SIZE {
            for i in 0..=(adapter.len() - KMER_SIZE) {
                let kmer = &adapter[i..i + KMER_SIZE];
                if let Some(hash) = hash_kmer(kmer) {
                    kmer_positions.entry(hash).or_default().push(i);
                }
            }
        }

        Self {
            kmer_positions,
            adapter: adapter.to_vec(),
            min_match_len,
        }
    }

    /// Detect adapter position using k-mer index.
    /// Returns the position where the adapter starts, or None if not found.
    #[inline]
    pub fn detect(&self, seq: &[u8], max_mismatch: usize) -> Option<usize> {
        if seq.len() < KMER_SIZE || self.adapter.is_empty() {
            return None;
        }

        let seq_len = seq.len();

        // Scan sequence for k-mer matches
        for i in 0..=(seq_len - KMER_SIZE) {
            let kmer = &seq[i..i + KMER_SIZE];
            let hash = match hash_kmer(kmer) {
                Some(h) => h,
                None => continue, // Skip k-mers with N
            };

            // Check if this k-mer exists in adapter
            if let Some(adapter_positions) = self.kmer_positions.get(&hash) {
                // For each position in adapter where this k-mer matches
                for &adapter_pos in adapter_positions {
                    // Calculate where adapter would start in sequence
                    let seq_adapter_start = i.saturating_sub(adapter_pos);

                    // Verify the full match
                    if let Some(pos) = self.verify_match(seq, seq_adapter_start, max_mismatch) {
                        if pos >= self.min_match_len {
                            return Some(pos);
                        }
                    }
                }
            }
        }

        None
    }

    /// Verify that adapter matches at the given position.
    #[inline]
    fn verify_match(&self, seq: &[u8], start: usize, max_mismatch: usize) -> Option<usize> {
        let seq_len = seq.len();
        let adapter_len = self.adapter.len();

        if start >= seq_len {
            return None;
        }

        let overlap_len = (seq_len - start).min(adapter_len);

        // Skip very short overlaps
        if overlap_len < KMER_SIZE {
            return None;
        }

        let max_allowed = (overlap_len / 8).max(1).min(max_mismatch);
        let mut mismatches = 0;

        for i in 0..overlap_len {
            if seq[start + i] != self.adapter[i] {
                mismatches += 1;
                if mismatches > max_allowed {
                    return None;
                }
            }
        }

        Some(start)
    }
}

/// Hash a k-mer to a 64-bit value.
/// Returns None if k-mer contains invalid bases (N).
#[inline]
fn hash_kmer(kmer: &[u8]) -> Option<u64> {
    let mut hash: u64 = 0;
    for &base in kmer {
        let bits = match base {
            b'A' | b'a' => 0u64,
            b'C' | b'c' => 1u64,
            b'G' | b'g' => 2u64,
            b'T' | b't' => 3u64,
            _ => return None, // N or invalid base
        };
        hash = (hash << 2) | bits;
    }
    Some(hash)
}

/// Pre-built adapter indices for fast trimming.
#[derive(Debug, Clone)]
pub struct AdapterIndices {
    pub r1_index: Option<AdapterKmerIndex>,
    pub r2_index: Option<AdapterKmerIndex>,
    pub additional_indices: Vec<AdapterKmerIndex>,
}

impl AdapterIndices {
    /// Build indices from adapter configuration.
    pub fn from_config(config: &AdapterConfig) -> Self {
        let r1_index = config.adapter_r1.as_ref().map(|a| {
            AdapterKmerIndex::new(a, config.min_match_length)
        });

        let r2_index = config.adapter_r2.as_ref().map(|a| {
            AdapterKmerIndex::new(a, config.min_match_length)
        });

        let additional_indices = config.adapter_list
            .iter()
            .map(|(_, a)| AdapterKmerIndex::new(a, config.min_match_length))
            .collect();

        Self {
            r1_index,
            r2_index,
            additional_indices,
        }
    }

    /// Detect adapter using pre-built indices.
    #[inline]
    pub fn detect(&self, seq: &[u8], max_mismatch: usize, min_match_length: usize) -> Option<usize> {
        let mut best_pos: Option<usize> = None;

        // Try R1 adapter
        if let Some(ref index) = self.r1_index {
            if let Some(pos) = index.detect(seq, max_mismatch) {
                if pos >= min_match_length {
                    best_pos = Some(pos);
                }
            }
        }

        // Try R2 adapter
        if let Some(ref index) = self.r2_index {
            if let Some(pos) = index.detect(seq, max_mismatch) {
                if pos >= min_match_length {
                    best_pos = match best_pos {
                        Some(prev) => Some(prev.min(pos)),
                        None => Some(pos),
                    };
                }
            }
        }

        // Try additional adapters
        for index in &self.additional_indices {
            if let Some(pos) = index.detect(seq, max_mismatch) {
                if pos >= min_match_length {
                    best_pos = match best_pos {
                        Some(prev) => Some(prev.min(pos)),
                        None => Some(pos),
                    };
                }
            }
        }

        best_pos
    }
}

/// Trim adapter using pre-built k-mer indices (fast path).
#[inline]
pub fn trim_adapter_indexed(seq: &[u8], indices: &AdapterIndices, config: &AdapterConfig) -> TrimResult {
    if seq.is_empty() {
        return TrimResult::empty();
    }

    match indices.detect(seq, config.max_mismatch, config.min_match_length) {
        Some(pos) => TrimResult::new(0, pos),
        None => TrimResult::full(seq.len()),
    }
}

// ============================================================================
// Built-in Adapter Database
// ============================================================================

/// Illumina TruSeq Read 1 adapter.
pub const ILLUMINA_TRUSEQ_R1: &[u8] = b"AGATCGGAAGAGCACACGTCTGAACTCCAGTCA";

/// Illumina TruSeq Read 2 adapter.
pub const ILLUMINA_TRUSEQ_R2: &[u8] = b"AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGT";

/// Nextera Read 1 adapter.
pub const NEXTERA_R1: &[u8] = b"CTGTCTCTTATACACATCT";

/// Nextera Read 2 adapter.
pub const NEXTERA_R2: &[u8] = b"CTGTCTCTTATACACATCT";

/// BGI adapter Read 1.
pub const BGI_R1: &[u8] = b"AAGTCGGAGGCCAAGCGGTCTTAGGAAGACAA";

/// BGI adapter Read 2.
pub const BGI_R2: &[u8] = b"AAGTCGGATCGTAGCCATGTCGTTCTGTGAGCCAAGGAGTTG";

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for adapter trimming.
#[derive(Debug, Clone)]
pub struct AdapterConfig {
    /// Adapter sequence for Read 1 (None = disabled).
    pub adapter_r1: Option<Vec<u8>>,
    /// Adapter sequence for Read 2 (None = disabled).
    pub adapter_r2: Option<Vec<u8>>,
    /// List of additional adapters (name, sequence pairs).
    pub adapter_list: Vec<(String, Vec<u8>)>,
    /// Enable automatic adapter detection from paired-end overlap.
    pub auto_detect: bool,
    /// Minimum overlap length for adapter detection (default: 30).
    pub min_overlap: usize,
    /// Maximum allowed mismatches in adapter alignment.
    pub max_mismatch: usize,
    /// Minimum match length to consider adapter found.
    pub min_match_length: usize,
    /// 5' adapter sequence for long read mode (fastplong compatible).
    pub start_adapter: Option<Vec<u8>>,
    /// 3' adapter sequence for long read mode (fastplong compatible).
    pub end_adapter: Option<Vec<u8>>,
    /// Distance threshold for long read adapter matching (ratio: 0.0-1.0, default: 0.25).
    pub distance_threshold: f64,
    /// Extend trimming N bases past adapter position (long mode only, default: 10).
    pub trimming_extension: usize,
}

impl Default for AdapterConfig {
    fn default() -> Self {
        Self {
            adapter_r1: Some(ILLUMINA_TRUSEQ_R1.to_vec()),
            adapter_r2: Some(ILLUMINA_TRUSEQ_R2.to_vec()),
            adapter_list: Vec::new(),
            auto_detect: false,
            min_overlap: 30,
            max_mismatch: 3,
            min_match_length: 10,
            start_adapter: None,
            end_adapter: None,
            distance_threshold: 0.25,
            trimming_extension: 10,
        }
    }
}

impl AdapterConfig {
    /// Create a new adapter config with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create config with no adapters (disabled).
    pub fn disabled() -> Self {
        Self {
            adapter_r1: None,
            adapter_r2: None,
            adapter_list: Vec::new(),
            auto_detect: false,
            min_overlap: 30,
            max_mismatch: 3,
            min_match_length: 10,
            start_adapter: None,
            end_adapter: None,
            distance_threshold: 0.25,
            trimming_extension: 10,
        }
    }

    /// Create config for Illumina TruSeq.
    pub fn truseq() -> Self {
        Self {
            adapter_r1: Some(ILLUMINA_TRUSEQ_R1.to_vec()),
            adapter_r2: Some(ILLUMINA_TRUSEQ_R2.to_vec()),
            ..Self::default()
        }
    }

    /// Create config for Nextera.
    pub fn nextera() -> Self {
        Self {
            adapter_r1: Some(NEXTERA_R1.to_vec()),
            adapter_r2: Some(NEXTERA_R2.to_vec()),
            ..Self::default()
        }
    }

    /// Set Read 1 adapter.
    pub fn with_adapter_r1(mut self, adapter: Vec<u8>) -> Self {
        self.adapter_r1 = Some(adapter);
        self
    }

    /// Set Read 2 adapter.
    pub fn with_adapter_r2(mut self, adapter: Vec<u8>) -> Self {
        self.adapter_r2 = Some(adapter);
        self
    }

    /// Enable/disable auto detection.
    pub fn with_auto_detect(mut self, enabled: bool) -> Self {
        self.auto_detect = enabled;
        self
    }

    /// Set minimum overlap for auto detection.
    pub fn with_min_overlap(mut self, overlap: usize) -> Self {
        self.min_overlap = overlap;
        self
    }

    /// Set maximum mismatches.
    pub fn with_max_mismatch(mut self, max: usize) -> Self {
        self.max_mismatch = max;
        self
    }

    /// Set adapter list from FASTA file.
    pub fn with_adapter_list(mut self, adapters: Vec<(String, Vec<u8>)>) -> Self {
        self.adapter_list = adapters;
        self
    }

    /// Set 5' (start) adapter for long read mode.
    pub fn with_start_adapter(mut self, adapter: Vec<u8>) -> Self {
        self.start_adapter = Some(adapter);
        self
    }

    /// Set 3' (end) adapter for long read mode.
    pub fn with_end_adapter(mut self, adapter: Vec<u8>) -> Self {
        self.end_adapter = Some(adapter);
        self
    }

    /// Set distance threshold for long read adapter matching.
    pub fn with_distance_threshold(mut self, threshold: f64) -> Self {
        self.distance_threshold = threshold;
        self
    }

    /// Set trimming extension (long mode only).
    pub fn with_trimming_extension(mut self, extension: usize) -> Self {
        self.trimming_extension = extension;
        self
    }
}

// ============================================================================
// Adapter Detection
// ============================================================================

/// Detect adapter position in a sequence.
///
/// Uses a simple semi-global alignment to find where the adapter starts in the read.
/// The adapter can be partially present at the 3' end.
///
/// # Arguments
/// * `seq` - The read sequence
/// * `adapter` - The adapter sequence to find
/// * `max_mismatch` - Maximum allowed mismatches
///
/// # Returns
/// Position where adapter starts (None if not found).
pub fn detect_adapter(seq: &[u8], adapter: &[u8], max_mismatch: usize) -> Option<usize> {
    if seq.is_empty() || adapter.is_empty() {
        return None;
    }

    let seq_len = seq.len();
    let adapter_len = adapter.len();

    // Try each starting position in the sequence
    // Adapter can start anywhere and extend past the read end
    for start in 0..seq_len {
        let overlap_len = (seq_len - start).min(adapter_len);

        // Skip very short overlaps
        if overlap_len < 8 {
            continue;
        }

        let mut mismatches = 0;
        let max_allowed = (overlap_len / 10).max(1).min(max_mismatch);

        for i in 0..overlap_len {
            if seq[start + i] != adapter[i] {
                mismatches += 1;
                if mismatches > max_allowed {
                    break;
                }
            }
        }

        if mismatches <= max_allowed {
            return Some(start);
        }
    }

    None
}

/// Trim adapter from a read sequence.
///
/// # Arguments
/// * `seq` - The read sequence
/// * `config` - Adapter configuration
///
/// # Returns
/// TrimResult indicating the range to keep (before adapter).
pub fn trim_adapter(seq: &[u8], config: &AdapterConfig) -> TrimResult {
    if seq.is_empty() {
        return TrimResult::empty();
    }

    let mut best_pos: Option<usize> = None;

    // Try R1 adapter first
    if let Some(ref adapter) = config.adapter_r1 {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                best_pos = Some(pos);
            }
        }
    }

    // Try R2 adapter
    if let Some(ref adapter) = config.adapter_r2 {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                // Use earlier position (best match)
                best_pos = match best_pos {
                    Some(prev) => Some(prev.min(pos)),
                    None => Some(pos),
                };
            }
        }
    }

    // Try all adapters from the list
    for (_name, adapter) in &config.adapter_list {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                best_pos = match best_pos {
                    Some(prev) => Some(prev.min(pos)),
                    None => Some(pos),
                };
            }
        }
    }

    match best_pos {
        Some(pos) => TrimResult::new(0, pos),
        None => TrimResult::full(seq.len()),
    }
}

/// Trim adapter from a read sequence with read type specification.
///
/// This is an optimized version that only searches for the relevant adapter:
/// - R1 reads: search for R1 adapter first, then R2, then additional
/// - R2 reads: search for R2 adapter first, then R1, then additional
///
/// # Arguments
/// * `seq` - The read sequence
/// * `config` - Adapter configuration
/// * `is_read2` - Whether this is read 2 in a paired-end pair
///
/// # Returns
/// TrimResult indicating the range to keep (before adapter).
#[inline]
pub fn trim_adapter_targeted(seq: &[u8], config: &AdapterConfig, is_read2: bool) -> TrimResult {
    if seq.is_empty() {
        return TrimResult::empty();
    }

    // Search for the primary adapter first (matching read type)
    let (primary_adapter, secondary_adapter) = if is_read2 {
        (&config.adapter_r2, &config.adapter_r1)
    } else {
        (&config.adapter_r1, &config.adapter_r2)
    };

    // Try primary adapter first
    if let Some(ref adapter) = primary_adapter {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                return TrimResult::new(0, pos);
            }
        }
    }

    // Try secondary adapter
    if let Some(ref adapter) = secondary_adapter {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                return TrimResult::new(0, pos);
            }
        }
    }

    // Try additional adapters
    for (_name, adapter) in &config.adapter_list {
        if let Some(pos) = detect_adapter(seq, adapter, config.max_mismatch) {
            if pos >= config.min_match_length {
                return TrimResult::new(0, pos);
            }
        }
    }

    TrimResult::full(seq.len())
}

/// Detect adapter from paired-end overlap (fastp algorithm).
///
/// When R1 and R2 overlap, the bases beyond the overlap in each read
/// are adapter sequences.
///
/// # Arguments
/// * `r1` - Read 1 sequence
/// * `r2` - Read 2 sequence (will be reverse complemented internally)
/// * `min_overlap` - Minimum overlap length to consider
///
/// # Returns
/// Tuple of (adapter_r1, adapter_r2) if detected.
pub fn detect_adapter_from_overlap(
    r1: &[u8],
    r2: &[u8],
    min_overlap: usize,
) -> Option<(Vec<u8>, Vec<u8>)> {
    if r1.len() < min_overlap || r2.len() < min_overlap {
        return None;
    }

    let r2_rc = reverse_complement(r2);

    // Try different overlap positions
    for overlap_len in min_overlap..=r1.len().min(r2_rc.len()) {
        let r1_start = r1.len() - overlap_len;
        let r1_overlap = &r1[r1_start..];
        let r2_overlap = &r2_rc[..overlap_len];

        // Check if they match
        let mismatches: usize = r1_overlap
            .iter()
            .zip(r2_overlap.iter())
            .map(|(a, b)| if a != b { 1 } else { 0 })
            .sum();

        let max_allowed = overlap_len / 10;
        if mismatches <= max_allowed {
            // Found overlap. Adapter is what's beyond the overlap.
            let adapter_r1 = if r1.len() > overlap_len {
                r2_rc[overlap_len..].to_vec()
            } else {
                Vec::new()
            };

            let adapter_r2 = if r2.len() > overlap_len {
                reverse_complement(&r1[..r1_start])
            } else {
                Vec::new()
            };

            if !adapter_r1.is_empty() || !adapter_r2.is_empty() {
                return Some((adapter_r1, adapter_r2));
            }
        }
    }

    None
}

/// Compute reverse complement of a DNA sequence.
#[inline]
pub fn reverse_complement(seq: &[u8]) -> Vec<u8> {
    seq.iter()
        .rev()
        .map(|&b| match b {
            b'A' | b'a' => b'T',
            b'T' | b't' => b'A',
            b'G' | b'g' => b'C',
            b'C' | b'c' => b'G',
            b'N' | b'n' => b'N',
            _ => b'N',
        })
        .collect()
}

/// Parse adapter sequences from a FASTA file.
///
/// # Arguments
/// * `path` - Path to the FASTA file
///
/// # Returns
/// Vector of (name, sequence) pairs.
///
/// # Example FASTA format
/// ```text
/// >adapter1
/// AGATCGGAAGAGC
/// >adapter2
/// CTGTCTCTTATACACATCT
/// ```
pub fn parse_adapter_fasta(path: &std::path::Path) -> std::io::Result<Vec<(String, Vec<u8>)>> {
    use std::fs::File;
    use std::io::{BufRead, BufReader};

    let file = File::open(path)?;
    let reader = BufReader::new(file);

    let mut adapters = Vec::new();
    let mut current_name: Option<String> = None;
    let mut current_seq = Vec::new();

    for line in reader.lines() {
        let line = line?;
        let trimmed = line.trim();

        if trimmed.is_empty() {
            continue;
        }

        if trimmed.starts_with('>') {
            // Save previous adapter if any
            if let Some(name) = current_name.take() {
                if !current_seq.is_empty() {
                    adapters.push((name, current_seq.clone()));
                    current_seq.clear();
                }
            }
            // Start new adapter
            current_name = Some(trimmed[1..].trim().to_string());
        } else {
            // Append sequence line
            current_seq.extend_from_slice(trimmed.as_bytes());
        }
    }

    // Save last adapter
    if let Some(name) = current_name {
        if !current_seq.is_empty() {
            adapters.push((name, current_seq));
        }
    }

    Ok(adapters)
}

// Legacy type alias for compatibility
pub type AdapterTrimmer = AdapterConfig;

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

    #[test]
    fn test_adapter_config_default() {
        let config = AdapterConfig::default();
        assert!(config.adapter_r1.is_some());
        assert!(config.adapter_r2.is_some());
        assert!(!config.auto_detect);
        assert_eq!(config.min_overlap, 30);
    }

    #[test]
    fn test_adapter_config_disabled() {
        let config = AdapterConfig::disabled();
        assert!(config.adapter_r1.is_none());
        assert!(config.adapter_r2.is_none());
    }

    #[test]
    fn test_adapter_config_truseq() {
        let config = AdapterConfig::truseq();
        assert_eq!(config.adapter_r1.as_deref(), Some(ILLUMINA_TRUSEQ_R1));
        assert_eq!(config.adapter_r2.as_deref(), Some(ILLUMINA_TRUSEQ_R2));
    }

    #[test]
    fn test_adapter_config_nextera() {
        let config = AdapterConfig::nextera();
        assert_eq!(config.adapter_r1.as_deref(), Some(NEXTERA_R1));
        assert_eq!(config.adapter_r2.as_deref(), Some(NEXTERA_R2));
    }

    #[test]
    fn test_detect_adapter_exact() {
        let adapter = b"AGATCGGAAGAG";
        let seq = b"ACGTACGTACGTACGTAAAAAAAGATCGGAAGAG";
        let pos = detect_adapter(seq, adapter, 1);
        assert!(pos.is_some());
        // Should find the adapter
        assert!(pos.unwrap() > 0);
    }

    #[test]
    fn test_detect_adapter_partial() {
        let adapter = b"AGATCGGAAGAGCACACGT";
        let seq = b"ACGTACGTACGTACGTAAAAAAAGATCGGA"; // Adapter starts near end
        let pos = detect_adapter(seq, adapter, 1);
        // Partial adapter at end should be detected
        assert!(pos.is_some());
    }

    #[test]
    fn test_detect_adapter_not_found() {
        let adapter = b"AGATCGGAAGAG";
        let seq = b"ACGTACGTACGTACGT"; // No adapter
        let pos = detect_adapter(seq, adapter, 0);
        assert!(pos.is_none());
    }

    #[test]
    fn test_detect_adapter_empty() {
        assert!(detect_adapter(&[], b"AGATC", 0).is_none());
        assert!(detect_adapter(b"ACGT", &[], 0).is_none());
    }

    #[test]
    fn test_trim_adapter() {
        let adapter = b"AGATCGGAAGAG";
        let seq = b"ACGTACGTACGTACGTAAAAAAAGATCGGAAGAG";
        let config = AdapterConfig::new()
            .with_adapter_r1(adapter.to_vec())
            .with_max_mismatch(1);
        let result = trim_adapter(seq, &config);
        assert!(result.end < seq.len());
    }

    #[test]
    fn test_trim_adapter_empty() {
        let config = AdapterConfig::default();
        let result = trim_adapter(&[], &config);
        assert!(result.is_empty());
    }

    #[test]
    fn test_trim_adapter_no_adapter_found() {
        let seq = b"ACGTACGTACGTACGT";
        let config = AdapterConfig::disabled();
        let result = trim_adapter(seq, &config);
        assert_eq!(result.start, 0);
        assert_eq!(result.end, seq.len());
    }

    #[test]
    fn test_reverse_complement() {
        assert_eq!(reverse_complement(b"ACGT"), b"ACGT");
        assert_eq!(reverse_complement(b"AAAA"), b"TTTT");
        assert_eq!(reverse_complement(b"GCGC"), b"GCGC");
        assert_eq!(reverse_complement(b"ATCGATCG"), b"CGATCGAT");
        assert_eq!(reverse_complement(b""), b"");
        assert_eq!(reverse_complement(b"N"), b"N");
    }

    #[test]
    fn test_reverse_complement_lowercase() {
        assert_eq!(reverse_complement(b"acgt"), b"ACGT");
        assert_eq!(reverse_complement(b"AcGt"), b"ACGT");
    }

    #[test]
    fn test_detect_adapter_from_overlap_short() {
        // Sequences too short for minimum overlap
        let result = detect_adapter_from_overlap(b"ACGT", b"ACGT", 30);
        assert!(result.is_none());
    }

    #[test]
    fn test_config_builder() {
        let config = AdapterConfig::new()
            .with_adapter_r1(b"ACGT".to_vec())
            .with_adapter_r2(b"TGCA".to_vec())
            .with_auto_detect(true)
            .with_min_overlap(20)
            .with_max_mismatch(5);
        assert_eq!(config.adapter_r1.as_deref(), Some(b"ACGT".as_slice()));
        assert_eq!(config.adapter_r2.as_deref(), Some(b"TGCA".as_slice()));
        assert!(config.auto_detect);
        assert_eq!(config.min_overlap, 20);
        assert_eq!(config.max_mismatch, 5);
    }

    #[test]
    fn test_adapter_constants() {
        // Verify adapter sequences are reasonable length
        assert!(ILLUMINA_TRUSEQ_R1.len() > 20);
        assert!(ILLUMINA_TRUSEQ_R2.len() > 20);
        assert!(NEXTERA_R1.len() > 10);
        assert!(NEXTERA_R2.len() > 10);
        assert!(BGI_R1.len() > 20);
        assert!(BGI_R2.len() > 20);
    }
}