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
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
//! JSON report generation.
//!
//! This module provides fastp-compatible JSON report output for QC statistics.
//! The output format is designed to be compatible with downstream tools that
//! expect fastp JSON format.

use crate::qc::{FilteringStats, QcStats};
use serde::Serialize;
use std::io::Write;

// ============================================================================
// JSON Report Configuration
// ============================================================================

/// Configuration for JSON report generation.
#[derive(Debug, Clone)]
pub struct JsonConfig {
    /// Whether to pretty-print the JSON output
    pub pretty: bool,
    /// Include timing information
    pub include_timing: bool,
}

impl Default for JsonConfig {
    fn default() -> Self {
        Self {
            pretty: true,
            include_timing: true,
        }
    }
}

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

    /// Set whether to pretty-print the output.
    pub fn with_pretty(mut self, pretty: bool) -> Self {
        self.pretty = pretty;
        self
    }

    /// Set whether to include timing information.
    pub fn with_timing(mut self, include: bool) -> Self {
        self.include_timing = include;
        self
    }
}

// ============================================================================
// fastp-compatible JSON Report Structures
// ============================================================================

/// Main JSON report structure (fastp-compatible).
#[derive(Debug, Clone, Serialize)]
pub struct JsonReport {
    /// Summary section
    pub summary: Summary,
    /// Read 1 statistics before filtering
    pub read1_before_filtering: ReadStats,
    /// Read 1 statistics after filtering
    pub read1_after_filtering: ReadStats,
    /// Read 2 statistics before filtering (paired-end only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read2_before_filtering: Option<ReadStats>,
    /// Read 2 statistics after filtering (paired-end only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read2_after_filtering: Option<ReadStats>,
    /// Filtering result summary
    pub filtering_result: FilteringResult,
    /// Duplication information
    pub duplication: DuplicationInfo,
    /// Adapter cutting statistics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_cutting: Option<AdapterStats>,
    /// Insert size statistics (paired-end only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub insert_size: Option<InsertSizeInfo>,
    /// Overlap-based correction statistics (paired-end only)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correction: Option<CorrectionInfo>,
    /// Command line used
    pub command: String,
}

/// Summary section of the report.
#[derive(Debug, Clone, Serialize)]
pub struct Summary {
    /// Tool version
    pub fastars_version: String,
    /// Sequencing type: "paired end" or "single end"
    pub sequencing_type: String,
    /// Statistics before filtering
    pub before_filtering: BeforeAfterSummary,
    /// Statistics after filtering
    pub after_filtering: BeforeAfterSummary,
}

/// Summary statistics for before/after filtering.
#[derive(Debug, Clone, Serialize)]
pub struct BeforeAfterSummary {
    /// Total reads
    pub total_reads: u64,
    /// Total bases
    pub total_bases: u64,
    /// Q20 bases count
    pub q20_bases: u64,
    /// Q30 bases count
    pub q30_bases: u64,
    /// Q20 rate (0.0-1.0)
    pub q20_rate: f64,
    /// Q30 rate (0.0-1.0)
    pub q30_rate: f64,
    /// Read 1 mean length
    pub read1_mean_length: f64,
    /// Read 2 mean length (if paired)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read2_mean_length: Option<f64>,
    /// GC content (0.0-1.0)
    pub gc_content: f64,
}

/// Per-read statistics with position-based data.
#[derive(Debug, Clone, Serialize)]
pub struct ReadStats {
    /// Total reads
    pub total_reads: u64,
    /// Total bases
    pub total_bases: u64,
    /// Q20 bases
    pub q20_bases: u64,
    /// Q30 bases
    pub q30_bases: u64,
    /// Mean quality score
    pub mean_quality: f64,
    /// Mean length
    pub mean_length: f64,
    /// GC content (0.0-1.0)
    pub gc_content: f64,
    /// Per-position quality curve (mean quality at each position)
    pub quality_curve: Vec<f64>,
    /// Per-position base content [A%, T%, G%, C%, N%]
    pub content_curves: ContentCurves,
    /// Quality histogram (Q0-Q93)
    pub quality_histogram: Vec<u64>,
    /// GC content histogram (0-100%)
    pub gc_histogram: Vec<u64>,
    /// Length distribution
    pub length_histogram: LengthHistogram,
    /// K-mer overrepresented sequences
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub overrepresented_sequences: Vec<OverrepresentedSeq>,
}

/// Base content curves (per-position percentages).
#[derive(Debug, Clone, Serialize)]
pub struct ContentCurves {
    /// A content per position
    #[serde(rename = "A")]
    pub a: Vec<f64>,
    /// T content per position
    #[serde(rename = "T")]
    pub t: Vec<f64>,
    /// G content per position
    #[serde(rename = "G")]
    pub g: Vec<f64>,
    /// C content per position
    #[serde(rename = "C")]
    pub c: Vec<f64>,
    /// N content per position
    #[serde(rename = "N")]
    pub n: Vec<f64>,
    /// GC content per position
    pub gc: Vec<f64>,
}

/// Length distribution histogram.
#[derive(Debug, Clone, Serialize)]
pub struct LengthHistogram {
    /// Minimum length
    pub min: usize,
    /// Maximum length
    pub max: usize,
    /// Mean length
    pub mean: f64,
    /// Median length
    pub median: usize,
    /// Length distribution (length -> count)
    pub distribution: Vec<LengthBin>,
}

/// A bin in the length histogram.
#[derive(Debug, Clone, Serialize)]
pub struct LengthBin {
    /// Length value
    pub length: usize,
    /// Count of reads with this length
    pub count: u64,
}

/// Overrepresented sequence entry.
#[derive(Debug, Clone, Serialize)]
pub struct OverrepresentedSeq {
    /// The sequence
    pub sequence: String,
    /// Number of occurrences
    pub count: u64,
    /// Percentage of total reads
    pub percentage: f64,
    /// Possible source (e.g., "Illumina adapter")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub possible_source: Option<String>,
}

/// Filtering result statistics.
#[derive(Debug, Clone, Default, Serialize)]
pub struct FilteringResult {
    /// Reads passed filter
    pub passed_filter_reads: u64,
    /// Reads filtered due to low quality
    pub low_quality_reads: u64,
    /// Reads filtered due to too many Ns
    pub too_many_n_reads: u64,
    /// Reads filtered due to short length
    pub too_short_reads: u64,
    /// Reads filtered due to long length
    pub too_long_reads: u64,
    /// Low complexity reads filtered
    pub low_complexity_reads: u64,
}

/// Duplication analysis information.
#[derive(Debug, Clone, Serialize)]
pub struct DuplicationInfo {
    /// Overall duplication rate (0.0-100.0)
    pub rate: f64,
    /// Duplication histogram (1x, 2x, 3x, ... 10+x)
    pub histogram: DuplicationHistogram,
}

/// Duplication level histogram.
#[derive(Debug, Clone, Serialize)]
pub struct DuplicationHistogram {
    /// Reads seen 1 time (unique)
    #[serde(rename = "1")]
    pub level_1: u64,
    /// Reads seen 2 times
    #[serde(rename = "2")]
    pub level_2: u64,
    /// Reads seen 3 times
    #[serde(rename = "3")]
    pub level_3: u64,
    /// Reads seen 4 times
    #[serde(rename = "4")]
    pub level_4: u64,
    /// Reads seen 5 times
    #[serde(rename = "5")]
    pub level_5: u64,
    /// Reads seen 6 times
    #[serde(rename = "6")]
    pub level_6: u64,
    /// Reads seen 7 times
    #[serde(rename = "7")]
    pub level_7: u64,
    /// Reads seen 8 times
    #[serde(rename = "8")]
    pub level_8: u64,
    /// Reads seen 9 times
    #[serde(rename = "9")]
    pub level_9: u64,
    /// Reads seen 10+ times
    #[serde(rename = "10+")]
    pub level_10_plus: u64,
}

/// Adapter cutting statistics.
#[derive(Debug, Clone, Serialize)]
pub struct AdapterStats {
    /// Adapter sequence for read 1
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_r1: Option<String>,
    /// Adapter sequence for read 2
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter_r2: Option<String>,
    /// Total reads with adapter trimmed
    pub reads_with_adapter: u64,
    /// Bases trimmed from adapters
    pub bases_trimmed: u64,
}

/// Insert size statistics (paired-end only).
#[derive(Debug, Clone, Serialize)]
pub struct InsertSizeInfo {
    /// Peak (mode) insert size
    pub peak: usize,
    /// Mean insert size
    pub mean: f64,
    /// Standard deviation
    pub std_dev: f64,
    /// Median insert size
    pub median: usize,
    /// Number of pairs with detected insert size
    pub count: u64,
    /// Detection rate (fraction of pairs with detectable overlap)
    pub detection_rate: f64,
    /// Insert size histogram
    pub histogram: Vec<u64>,
}

/// Overlap-based correction statistics (paired-end only).
#[derive(Debug, Clone, Default, Serialize)]
pub struct CorrectionInfo {
    /// Total number of read pairs processed for correction
    pub pairs_processed: u64,
    /// Number of pairs where overlap was found
    pub pairs_with_overlap: u64,
    /// Number of pairs that were corrected (at least one base changed)
    pub pairs_corrected: u64,
    /// Total number of bases corrected
    pub bases_corrected: u64,
    /// Number of bases corrected in R1
    pub bases_corrected_r1: u64,
    /// Number of bases corrected in R2
    pub bases_corrected_r2: u64,
    /// Overlap detection rate (percentage)
    pub overlap_rate: f64,
    /// Correction rate (percentage of pairs corrected)
    pub correction_rate: f64,
}

impl CorrectionInfo {
    /// Create CorrectionInfo from CorrectionStats.
    pub fn from_stats(stats: &crate::correction::CorrectionStats) -> Self {
        Self {
            pairs_processed: stats.pairs_processed,
            pairs_with_overlap: stats.pairs_with_overlap,
            pairs_corrected: stats.pairs_corrected,
            bases_corrected: stats.bases_corrected,
            bases_corrected_r1: stats.bases_corrected_r1,
            bases_corrected_r2: stats.bases_corrected_r2,
            overlap_rate: stats.overlap_rate(),
            correction_rate: stats.correction_rate(),
        }
    }
}

impl InsertSizeInfo {
    /// Create InsertSizeInfo from InsertSizeStats.
    pub fn from_stats(stats: &crate::qc::InsertSizeStats) -> Self {
        Self {
            peak: stats.peak(),
            mean: stats.mean(),
            std_dev: stats.std_dev(),
            median: stats.median(),
            count: stats.count(),
            detection_rate: stats.detection_rate(),
            histogram: stats.histogram().to_vec(),
        }
    }
}

// ============================================================================
// Timing Information
// ============================================================================

/// Timing information for the processing run.
#[derive(Debug, Clone, Serialize)]
pub struct TimingInfo {
    /// Total processing time in seconds
    pub total_seconds: f64,
    /// Reads processed per second
    pub reads_per_second: f64,
    /// Bases processed per second
    pub bases_per_second: f64,
}

// ============================================================================
// Report Building
// ============================================================================

impl JsonReport {
    /// Create a new JSON report from filtering statistics.
    pub fn from_filtering_stats(
        filtering_stats: &FilteringStats,
        command: String,
    ) -> Self {
        let is_paired = false; // TODO: Support paired-end detection
        let sequencing_type = if is_paired { "paired end" } else { "single end" };

        Self {
            summary: Summary {
                fastars_version: env!("CARGO_PKG_VERSION").to_string(),
                sequencing_type: sequencing_type.to_string(),
                before_filtering: BeforeAfterSummary::from_stats(&filtering_stats.before),
                after_filtering: BeforeAfterSummary::from_stats(&filtering_stats.after),
            },
            read1_before_filtering: ReadStats::from_qc_stats(&filtering_stats.before),
            read1_after_filtering: ReadStats::from_qc_stats(&filtering_stats.after),
            read2_before_filtering: None,
            read2_after_filtering: None,
            filtering_result: FilteringResult {
                passed_filter_reads: filtering_stats.after.total_reads,
                low_quality_reads: 0, // TODO: Track specific filter reasons
                too_many_n_reads: 0,
                too_short_reads: 0,
                too_long_reads: 0,
                low_complexity_reads: 0,
            },
            duplication: DuplicationInfo::from_stats(&filtering_stats.after),
            adapter_cutting: None,
            insert_size: filtering_stats.after.insert_size().map(InsertSizeInfo::from_stats),
            correction: None,
            command,
        }
    }

    /// Create a new JSON report from single QC stats (before-only mode).
    pub fn from_qc_stats(stats: &QcStats, command: String) -> Self {
        let sequencing_type = "single end";

        Self {
            summary: Summary {
                fastars_version: env!("CARGO_PKG_VERSION").to_string(),
                sequencing_type: sequencing_type.to_string(),
                before_filtering: BeforeAfterSummary::from_stats(stats),
                after_filtering: BeforeAfterSummary::from_stats(stats),
            },
            read1_before_filtering: ReadStats::from_qc_stats(stats),
            read1_after_filtering: ReadStats::from_qc_stats(stats),
            read2_before_filtering: None,
            read2_after_filtering: None,
            filtering_result: FilteringResult::default(),
            duplication: DuplicationInfo::from_stats(stats),
            adapter_cutting: None,
            insert_size: stats.insert_size().map(InsertSizeInfo::from_stats),
            correction: None,
            command,
        }
    }

    /// Create a new JSON report from before/after QC stats with paired-end support.
    pub fn from_qc_stats_pair(
        before: &QcStats,
        after: &QcStats,
        is_paired: bool,
        command: String,
    ) -> Self {
        let sequencing_type = if is_paired { "paired end" } else { "single end" };

        let mut summary_before = BeforeAfterSummary::from_stats(before);
        let mut summary_after = BeforeAfterSummary::from_stats(after);

        // For paired-end, set read2 mean length (same as read1 for now)
        if is_paired {
            summary_before.read2_mean_length = Some(summary_before.read1_mean_length);
            summary_after.read2_mean_length = Some(summary_after.read1_mean_length);
        }

        Self {
            summary: Summary {
                fastars_version: env!("CARGO_PKG_VERSION").to_string(),
                sequencing_type: sequencing_type.to_string(),
                before_filtering: summary_before,
                after_filtering: summary_after,
            },
            read1_before_filtering: ReadStats::from_qc_stats(before),
            read1_after_filtering: ReadStats::from_qc_stats(after),
            read2_before_filtering: if is_paired {
                Some(ReadStats::from_qc_stats(before))
            } else {
                None
            },
            read2_after_filtering: if is_paired {
                Some(ReadStats::from_qc_stats(after))
            } else {
                None
            },
            filtering_result: FilteringResult {
                passed_filter_reads: after.total_reads,
                low_quality_reads: before.total_reads.saturating_sub(after.total_reads),
                too_many_n_reads: 0,
                too_short_reads: 0,
                too_long_reads: 0,
                low_complexity_reads: 0,
            },
            duplication: DuplicationInfo::from_stats(after),
            adapter_cutting: None,
            insert_size: after.insert_size().map(InsertSizeInfo::from_stats),
            correction: None,
            command,
        }
    }

    /// Set adapter cutting statistics.
    pub fn with_adapter_stats(mut self, adapter_stats: AdapterStats) -> Self {
        self.adapter_cutting = Some(adapter_stats);
        self
    }

    /// Set correction statistics (for paired-end overlap correction).
    pub fn with_correction(mut self, correction: CorrectionInfo) -> Self {
        self.correction = Some(correction);
        self
    }

    /// Set read 2 statistics (for paired-end).
    pub fn with_read2_stats(
        mut self,
        before: ReadStats,
        after: ReadStats,
    ) -> Self {
        self.read2_before_filtering = Some(before);
        self.read2_after_filtering = Some(after);
        self.summary.sequencing_type = "paired end".to_string();
        self
    }

    /// Set insert size statistics.
    pub fn with_insert_size(mut self, insert_size: InsertSizeInfo) -> Self {
        self.insert_size = Some(insert_size);
        self
    }
}

impl BeforeAfterSummary {
    /// Create summary from QC stats.
    pub fn from_stats(stats: &QcStats) -> Self {
        let q20_rate = stats.q20_percent() / 100.0;
        let q30_rate = stats.q30_percent() / 100.0;
        let q20_bases = (stats.total_bases as f64 * q20_rate) as u64;
        let q30_bases = (stats.total_bases as f64 * q30_rate) as u64;

        Self {
            total_reads: stats.total_reads,
            total_bases: stats.total_bases,
            q20_bases,
            q30_bases,
            q20_rate,
            q30_rate,
            read1_mean_length: stats.mean_length(),
            read2_mean_length: None,
            gc_content: stats.mean_gc() / 100.0,
        }
    }
}

impl ReadStats {
    /// Create ReadStats from QcStats.
    pub fn from_qc_stats(stats: &QcStats) -> Self {
        let q20_rate = stats.q20_percent() / 100.0;
        let q30_rate = stats.q30_percent() / 100.0;
        let q20_bases = (stats.total_bases as f64 * q20_rate) as u64;
        let q30_bases = (stats.total_bases as f64 * q30_rate) as u64;

        // Build quality curve from position stats
        let quality_curve: Vec<f64> = stats.quality.position_stats()
            .iter()
            .map(|(sum, count)| {
                if *count == 0 {
                    0.0
                } else {
                    *sum as f64 / *count as f64
                }
            })
            .collect();

        // Build content curves from base content
        let positions = stats.base_content.len();
        let mut a_curve = Vec::with_capacity(positions);
        let mut t_curve = Vec::with_capacity(positions);
        let mut g_curve = Vec::with_capacity(positions);
        let mut c_curve = Vec::with_capacity(positions);
        let mut n_curve = Vec::with_capacity(positions);
        let mut gc_curve = Vec::with_capacity(positions);

        for pos in 0..positions {
            let ratios = stats.base_content.get_ratios(pos);
            a_curve.push(ratios[0] * 100.0);
            t_curve.push(ratios[1] * 100.0);
            g_curve.push(ratios[2] * 100.0);
            c_curve.push(ratios[3] * 100.0);
            n_curve.push(ratios[4] * 100.0);
            gc_curve.push((ratios[2] + ratios[3]) * 100.0);
        }

        // Build length histogram
        let length_dist: Vec<LengthBin> = stats.length.distribution()
            .iter()
            .map(|(&len, &count)| LengthBin { length: len, count })
            .collect();

        // Build overrepresented sequences
        let overrep: Vec<OverrepresentedSeq> = stats.kmer.top_overrepresented()
            .into_iter()
            .filter(|(_, count)| {
                let pct = (*count as f64 / stats.total_reads.max(1) as f64) * 100.0;
                pct >= 0.1 // Only include if >= 0.1%
            })
            .map(|(seq, count)| {
                let percentage = (count as f64 / stats.total_reads.max(1) as f64) * 100.0;
                OverrepresentedSeq {
                    sequence: String::from_utf8_lossy(&seq).to_string(),
                    count,
                    percentage,
                    possible_source: None, // TODO: Adapter detection
                }
            })
            .collect();

        Self {
            total_reads: stats.total_reads,
            total_bases: stats.total_bases,
            q20_bases,
            q30_bases,
            mean_quality: stats.mean_quality(),
            mean_length: stats.mean_length(),
            gc_content: stats.mean_gc() / 100.0,
            quality_curve,
            content_curves: ContentCurves {
                a: a_curve,
                t: t_curve,
                g: g_curve,
                c: c_curve,
                n: n_curve,
                gc: gc_curve,
            },
            quality_histogram: stats.quality.histogram().to_vec(),
            gc_histogram: stats.gc.histogram().to_vec(),
            length_histogram: LengthHistogram {
                min: stats.length.min_length(),
                max: stats.length.max_length(),
                mean: stats.mean_length(),
                median: stats.length.median_length(),
                distribution: length_dist,
            },
            overrepresented_sequences: overrep,
        }
    }
}

impl DuplicationInfo {
    /// Create duplication info from QC stats.
    pub fn from_stats(stats: &QcStats) -> Self {
        let hist = stats.duplication.histogram_snapshot();

        Self {
            rate: stats.duplication_rate(),
            histogram: DuplicationHistogram {
                level_1: hist[0],
                level_2: hist[1],
                level_3: hist[2],
                level_4: hist[3],
                level_5: hist[4],
                level_6: hist[5],
                level_7: hist[6],
                level_8: hist[7],
                level_9: hist[8],
                level_10_plus: hist[9],
            },
        }
    }
}

// ============================================================================
// Report Writing Functions
// ============================================================================

/// Generate a fastp-compatible JSON report from filtering statistics.
pub fn write_json_report<W: Write>(stats: &QcStats, writer: &mut W) -> anyhow::Result<()> {
    let report = JsonReport::from_qc_stats(stats, String::new());
    serde_json::to_writer_pretty(writer, &report)?;
    Ok(())
}

/// Generate a JSON report with configuration options.
pub fn write_json_report_with_config<W: Write>(
    stats: &QcStats,
    config: &JsonConfig,
    writer: &mut W,
) -> anyhow::Result<()> {
    let report = JsonReport::from_qc_stats(stats, String::new());

    if config.pretty {
        serde_json::to_writer_pretty(writer, &report)?;
    } else {
        serde_json::to_writer(writer, &report)?;
    }

    Ok(())
}

/// Generate a JSON report from filtering stats (before/after comparison).
pub fn write_filtering_json_report<W: Write>(
    filtering_stats: &FilteringStats,
    command: &str,
    writer: &mut W,
) -> anyhow::Result<()> {
    let report = JsonReport::from_filtering_stats(filtering_stats, command.to_string());
    serde_json::to_writer_pretty(writer, &report)?;
    Ok(())
}

/// Generate a JSON report with full control over all options.
pub fn write_full_json_report<W: Write>(
    report: &JsonReport,
    config: &JsonConfig,
    writer: &mut W,
) -> anyhow::Result<()> {
    if config.pretty {
        serde_json::to_writer_pretty(writer, report)?;
    } else {
        serde_json::to_writer(writer, report)?;
    }
    Ok(())
}

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

    fn create_test_stats() -> QcStats {
        let mut stats = QcStats::new(Mode::Short);
        // Add some test data
        stats.update_raw(b"ATGCATGC", b"IIIIIIII"); // Q40
        stats.update_raw(b"GCTAGCTA", b"????????"); // Q30
        stats.update_raw(b"ATATATATAT", b"5555555555"); // Q20
        stats
    }

    #[test]
    fn test_write_json_report() {
        let stats = create_test_stats();
        let mut output = Vec::new();
        write_json_report(&stats, &mut output).unwrap();

        assert!(!output.is_empty());
        let json_str = String::from_utf8(output).unwrap();
        assert!(json_str.contains("fastars_version"));
        assert!(json_str.contains("read1_before_filtering"));
    }

    #[test]
    fn test_json_report_structure() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, "fastars -i test.fq".to_string());

        assert_eq!(report.summary.sequencing_type, "single end");
        assert_eq!(report.read1_before_filtering.total_reads, 3);
        assert_eq!(report.command, "fastars -i test.fq");
    }

    #[test]
    fn test_json_report_quality_curve() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, String::new());

        // Quality curve should have entries
        assert!(!report.read1_before_filtering.quality_curve.is_empty());
    }

    #[test]
    fn test_json_report_content_curves() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, String::new());

        let content = &report.read1_before_filtering.content_curves;
        assert!(!content.a.is_empty());
        assert!(!content.t.is_empty());
        assert!(!content.g.is_empty());
        assert!(!content.c.is_empty());
    }

    #[test]
    fn test_json_report_length_histogram() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, String::new());

        let length = &report.read1_before_filtering.length_histogram;
        assert!(length.min > 0);
        assert!(length.max >= length.min);
    }

    #[test]
    fn test_json_report_duplication() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, String::new());

        assert!(report.duplication.rate >= 0.0);
        assert!(report.duplication.rate <= 100.0);
    }

    #[test]
    fn test_json_config_compact() {
        let stats = create_test_stats();
        let config = JsonConfig::new().with_pretty(false);

        let mut output = Vec::new();
        write_json_report_with_config(&stats, &config, &mut output).unwrap();

        let json_str = String::from_utf8(output).unwrap();
        // Compact JSON should not have newlines in the middle
        assert!(!json_str.contains("\n  "));
    }

    #[test]
    fn test_filtering_stats_report() {
        let mut filtering_stats = FilteringStats::new(Mode::Short);
        filtering_stats.before.update_raw(b"ATGC", b"IIII");
        filtering_stats.before.update_raw(b"GCTA", b"!!!!");
        filtering_stats.after.update_raw(b"ATGC", b"IIII");

        let mut output = Vec::new();
        write_filtering_json_report(&filtering_stats, "fastars -i test.fq", &mut output).unwrap();

        let json_str = String::from_utf8(output).unwrap();
        assert!(json_str.contains("filtering_result"));
        assert!(json_str.contains("passed_filter_reads"));
    }

    #[test]
    fn test_json_report_serialization() {
        let stats = create_test_stats();
        let report = JsonReport::from_qc_stats(&stats, String::new());

        // Verify it can be serialized to JSON
        let json = serde_json::to_string(&report).unwrap();
        assert!(!json.is_empty());

        // Verify the JSON is valid by parsing it back
        let _: serde_json::Value = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn test_before_after_summary() {
        let stats = create_test_stats();
        let summary = BeforeAfterSummary::from_stats(&stats);

        assert_eq!(summary.total_reads, 3);
        assert!(summary.gc_content >= 0.0 && summary.gc_content <= 1.0);
        assert!(summary.q20_rate >= 0.0 && summary.q20_rate <= 1.0);
        assert!(summary.q30_rate >= 0.0 && summary.q30_rate <= 1.0);
    }

    #[test]
    fn test_read_stats_from_empty() {
        let stats = QcStats::new(Mode::Short);
        let read_stats = ReadStats::from_qc_stats(&stats);

        assert_eq!(read_stats.total_reads, 0);
        assert_eq!(read_stats.total_bases, 0);
        assert!(read_stats.quality_curve.is_empty());
    }

    #[test]
    fn test_json_report_with_adapter_stats() {
        let stats = create_test_stats();
        let adapter_stats = AdapterStats {
            adapter_r1: Some("AGATCGGAAGAG".to_string()),
            adapter_r2: None,
            reads_with_adapter: 100,
            bases_trimmed: 500,
        };

        let report = JsonReport::from_qc_stats(&stats, String::new())
            .with_adapter_stats(adapter_stats);

        assert!(report.adapter_cutting.is_some());
        let adapter = report.adapter_cutting.unwrap();
        assert_eq!(adapter.reads_with_adapter, 100);
    }

    #[test]
    fn test_json_report_paired_end() {
        let stats = create_test_stats();
        let read2_before = ReadStats::from_qc_stats(&stats);
        let read2_after = ReadStats::from_qc_stats(&stats);

        let report = JsonReport::from_qc_stats(&stats, String::new())
            .with_read2_stats(read2_before, read2_after);

        assert_eq!(report.summary.sequencing_type, "paired end");
        assert!(report.read2_before_filtering.is_some());
        assert!(report.read2_after_filtering.is_some());
    }
}