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
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
//! HTML report generation.
//!
//! This module provides interactive HTML report output with Chart.js visualizations.
//! The report includes quality distribution, base content, GC content, length
//! distribution, and duplication analysis plots.

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

// ============================================================================
// HTML Report Configuration
// ============================================================================

/// Configuration for HTML report generation.
#[derive(Debug, Clone)]
pub struct HtmlConfig {
    /// Report title
    pub title: String,
    /// Include interactive charts
    pub interactive: bool,
    /// Chart width in pixels
    pub chart_width: u32,
    /// Chart height in pixels
    pub chart_height: u32,
}

impl Default for HtmlConfig {
    fn default() -> Self {
        Self {
            title: "Fastars QC Report".to_string(),
            interactive: true,
            chart_width: 800,
            chart_height: 400,
        }
    }
}

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

    /// Set the report title.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Enable or disable interactive charts.
    pub fn with_interactive(mut self, interactive: bool) -> Self {
        self.interactive = interactive;
        self
    }

    /// Set chart dimensions.
    pub fn with_dimensions(mut self, width: u32, height: u32) -> Self {
        self.chart_width = width;
        self.chart_height = height;
        self
    }
}

// ============================================================================
// Embedded JavaScript libraries for offline support
// ============================================================================

/// Plotly.js library (embedded for offline use)
const PLOTLY_EMBEDDED: &str = include_str!("plotly.min.js");

// ============================================================================
// HTML Template
// ============================================================================

/// Generate the HTML report head section with styles
fn write_html_head<W: Write>(writer: &mut W, config: &HtmlConfig) -> anyhow::Result<()> {
    writeln!(writer, "<!DOCTYPE html>")?;
    writeln!(writer, "<html lang=\"en\">")?;
    writeln!(writer, "<head>")?;
    writeln!(writer, "  <meta charset=\"UTF-8\">")?;
    writeln!(writer, "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")?;
    writeln!(writer, "  <title>{}</title>", config.title)?;
    // Embedded Plotly.js for offline support
    writeln!(writer, "  <script>{}</script>", PLOTLY_EMBEDDED)?;
    writeln!(writer, "  <style>")?;
    writeln!(writer, "{}", include_str!("html_template.css"))?;
    writeln!(writer, "  </style>")?;
    writeln!(writer, "</head>")?;
    Ok(())
}

/// Generate the summary statistics table
fn write_summary_table<W: Write>(
    writer: &mut W,
    stats_before: &QcStats,
    stats_after: Option<&QcStats>,
) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Summary Statistics</h2>")?;
    writeln!(writer, "    <table class=\"summary-table\">")?;
    writeln!(writer, "      <thead>")?;
    writeln!(writer, "        <tr>")?;
    writeln!(writer, "          <th>Metric</th>")?;
    writeln!(writer, "          <th>Before Filtering</th>")?;
    if stats_after.is_some() {
        writeln!(writer, "          <th>After Filtering</th>")?;
    }
    writeln!(writer, "        </tr>")?;
    writeln!(writer, "      </thead>")?;
    writeln!(writer, "      <tbody>")?;

    // Total Reads
    write_table_row(
        writer,
        "Total Reads",
        &format_number(stats_before.total_reads),
        stats_after.map(|s| format_number(s.total_reads)),
    )?;

    // Total Bases
    write_table_row(
        writer,
        "Total Bases",
        &format_bases(stats_before.total_bases),
        stats_after.map(|s| format_bases(s.total_bases)),
    )?;

    // Mean Length
    write_table_row(
        writer,
        "Mean Length",
        &format!("{:.1} bp", stats_before.mean_length()),
        stats_after.map(|s| format!("{:.1} bp", s.mean_length())),
    )?;

    // Mean Quality
    write_table_row(
        writer,
        "Mean Quality",
        &format!("Q{:.1}", stats_before.mean_quality()),
        stats_after.map(|s| format!("Q{:.1}", s.mean_quality())),
    )?;

    // Q20 Rate
    write_table_row(
        writer,
        "Q20 Rate",
        &format!("{:.2}%", stats_before.q20_percent()),
        stats_after.map(|s| format!("{:.2}%", s.q20_percent())),
    )?;

    // Q30 Rate
    write_table_row(
        writer,
        "Q30 Rate",
        &format!("{:.2}%", stats_before.q30_percent()),
        stats_after.map(|s| format!("{:.2}%", s.q30_percent())),
    )?;

    // GC Content
    write_table_row(
        writer,
        "GC Content",
        &format!("{:.2}%", stats_before.mean_gc()),
        stats_after.map(|s| format!("{:.2}%", s.mean_gc())),
    )?;

    // Duplication Rate
    write_table_row(
        writer,
        "Duplication Rate",
        &format!("{:.2}%", stats_before.duplication_rate()),
        stats_after.map(|s| format!("{:.2}%", s.duplication_rate())),
    )?;

    // N50 (for long reads)
    if stats_before.mode() == Mode::Long || stats_before.n50() > 0 {
        write_table_row(
            writer,
            "N50",
            &format!("{} bp", format_number(stats_before.n50() as u64)),
            stats_after.map(|s| format!("{} bp", format_number(s.n50() as u64))),
        )?;
    }

    writeln!(writer, "      </tbody>")?;
    writeln!(writer, "    </table>")?;
    writeln!(writer, "  </div>")?;
    Ok(())
}

/// Write a table row with before/after values
fn write_table_row<W: Write>(
    writer: &mut W,
    metric: &str,
    before: &str,
    after: Option<String>,
) -> anyhow::Result<()> {
    writeln!(writer, "        <tr>")?;
    writeln!(writer, "          <td>{}</td>", metric)?;
    writeln!(writer, "          <td>{}</td>", before)?;
    if let Some(after_val) = after {
        writeln!(writer, "          <td>{}</td>", after_val)?;
    }
    writeln!(writer, "        </tr>")?;
    Ok(())
}

/// Generate the quality distribution chart
fn write_quality_chart<W: Write>(
    writer: &mut W,
    stats_before: &QcStats,
    stats_after: Option<&QcStats>,
) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Per-Position Quality Distribution</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"qualityChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    // Generate quality curve data
    let quality_before: Vec<f64> = stats_before
        .quality
        .position_stats()
        .iter()
        .map(|(sum, count)| {
            if *count == 0 {
                0.0
            } else {
                *sum as f64 / *count as f64
            }
        })
        .collect();

    let quality_after: Option<Vec<f64>> = stats_after.map(|s| {
        s.quality
            .position_stats()
            .iter()
            .map(|(sum, count)| {
                if *count == 0 {
                    0.0
                } else {
                    *sum as f64 / *count as f64
                }
            })
            .collect()
    });

    let positions: Vec<usize> = (1..=quality_before.len()).collect();

    // Plotly.js chart
    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var traces = [")?;
    writeln!(writer, "        {{")?;
    writeln!(writer, "          x: {:?},", positions)?;
    writeln!(writer, "          y: {:?},", quality_before)?;
    writeln!(writer, "          type: 'scatter',")?;
    writeln!(writer, "          mode: 'lines',")?;
    writeln!(writer, "          name: 'Before Filtering',")?;
    writeln!(writer, "          line: {{ color: '#bd93f9', width: 2 }},")?;
    writeln!(writer, "          fill: 'tozeroy',")?;
    writeln!(writer, "          fillcolor: 'rgba(189, 147, 249, 0.1)'")?;
    writeln!(writer, "        }}")?;
    if let Some(ref after) = quality_after {
        writeln!(writer, "        ,{{")?;
        writeln!(writer, "          x: {:?},", (1..=after.len()).collect::<Vec<_>>())?;
        writeln!(writer, "          y: {:?},", after)?;
        writeln!(writer, "          type: 'scatter',")?;
        writeln!(writer, "          mode: 'lines',")?;
        writeln!(writer, "          name: 'After Filtering',")?;
        writeln!(writer, "          line: {{ color: '#50fa7b', width: 2 }},")?;
        writeln!(writer, "          fill: 'tozeroy',")?;
        writeln!(writer, "          fillcolor: 'rgba(80, 250, 123, 0.1)'")?;
        writeln!(writer, "        }}")?;
    }
    writeln!(writer, "      ];")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Mean Quality Score by Position', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Position (bp)', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Quality Score', gridcolor: '#44475a', zerolinecolor: '#44475a', range: [0, 45] }},")?;
    writeln!(writer, "        legend: {{ font: {{ color: '#f8f8f2' }} }},")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('qualityChart', traces, layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the base content chart
fn write_base_content_chart<W: Write>(
    writer: &mut W,
    stats: &QcStats,
) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Per-Position Base Content</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"baseContentChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    // Generate base content data
    let positions = stats.base_content.len();
    let mut a_content = Vec::with_capacity(positions);
    let mut t_content = Vec::with_capacity(positions);
    let mut g_content = Vec::with_capacity(positions);
    let mut c_content = Vec::with_capacity(positions);

    for pos in 0..positions {
        let ratios = stats.base_content.get_ratios(pos);
        a_content.push(ratios[0] * 100.0);
        t_content.push(ratios[1] * 100.0);
        g_content.push(ratios[2] * 100.0);
        c_content.push(ratios[3] * 100.0);
    }

    let pos_labels: Vec<usize> = (1..=positions).collect();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var traces = [")?;
    writeln!(writer, "        {{ x: {:?}, y: {:?}, type: 'scatter', mode: 'lines', name: 'A', line: {{ color: '#50fa7b', width: 2 }} }},", pos_labels, a_content)?;
    writeln!(writer, "        {{ x: {:?}, y: {:?}, type: 'scatter', mode: 'lines', name: 'T', line: {{ color: '#ff5555', width: 2 }} }},", pos_labels, t_content)?;
    writeln!(writer, "        {{ x: {:?}, y: {:?}, type: 'scatter', mode: 'lines', name: 'G', line: {{ color: '#8be9fd', width: 2 }} }},", pos_labels, g_content)?;
    writeln!(writer, "        {{ x: {:?}, y: {:?}, type: 'scatter', mode: 'lines', name: 'C', line: {{ color: '#bd93f9', width: 2 }} }}", pos_labels, c_content)?;
    writeln!(writer, "      ];")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Base Content (%)', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Position (bp)', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Percentage', gridcolor: '#44475a', zerolinecolor: '#44475a', range: [0, 100] }},")?;
    writeln!(writer, "        legend: {{ font: {{ color: '#f8f8f2' }} }},")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('baseContentChart', traces, layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the GC content histogram chart
fn write_gc_chart<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>GC Content Distribution</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"gcChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    let gc_histogram: Vec<u64> = stats.gc.histogram().to_vec();
    let gc_labels: Vec<u8> = (0..=100).collect();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var trace = {{")?;
    writeln!(writer, "        x: {:?},", gc_labels)?;
    writeln!(writer, "        y: {:?},", gc_histogram)?;
    writeln!(writer, "        type: 'bar',")?;
    writeln!(writer, "        name: 'Read Count',")?;
    writeln!(writer, "        marker: {{ color: 'rgba(80, 250, 123, 0.7)', line: {{ color: '#50fa7b', width: 1 }} }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'GC Content Histogram', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'GC Content (%)', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Read Count', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        bargap: 0.05,")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('gcChart', [trace], layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the length distribution chart
fn write_length_chart<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Read Length Distribution</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"lengthChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    // Collect and sort length distribution
    let mut lengths: Vec<(usize, u64)> = stats
        .length
        .distribution()
        .iter()
        .map(|(&len, &count)| (len, count))
        .collect();
    lengths.sort_by_key(|(len, _)| *len);

    let labels: Vec<usize> = lengths.iter().map(|(len, _)| *len).collect();
    let counts: Vec<u64> = lengths.iter().map(|(_, count)| *count).collect();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var trace = {{")?;
    writeln!(writer, "        x: {:?},", labels)?;
    writeln!(writer, "        y: {:?},", counts)?;
    writeln!(writer, "        type: 'bar',")?;
    writeln!(writer, "        name: 'Read Count',")?;
    writeln!(writer, "        marker: {{ color: 'rgba(139, 233, 253, 0.7)', line: {{ color: '#8be9fd', width: 1 }} }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Read Length Distribution', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Read Length (bp)', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Read Count', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        bargap: 0.05,")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('lengthChart', [trace], layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the duplication rate chart
fn write_duplication_chart<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Sequence Duplication Levels</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"dupChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    let hist = stats.duplication.histogram_snapshot();
    let labels = vec!["1", "2", "3", "4", "5", "6", "7", "8", "9", "10+"];
    let counts: Vec<u64> = hist.to_vec();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var trace = {{")?;
    writeln!(writer, "        x: {:?},", labels)?;
    writeln!(writer, "        y: {:?},", counts)?;
    writeln!(writer, "        type: 'bar',")?;
    writeln!(writer, "        name: 'Read Count',")?;
    writeln!(writer, "        marker: {{ color: 'rgba(255, 121, 198, 0.7)', line: {{ color: '#ff79c6', width: 1 }} }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Duplication Level Distribution', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Duplication Level', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Read Count', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        bargap: 0.2,")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('dupChart', [trace], layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the insert size distribution chart (paired-end only)
fn write_insert_size_chart<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    // Only show if insert size data is available
    let insert_size = match stats.insert_size() {
        Some(is) if is.has_data() => is,
        _ => return Ok(()),
    };

    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Insert Size Distribution</h2>")?;
    writeln!(writer, "    <p>Peak: {} bp | Mean: {:.1} bp | Std Dev: {:.1} bp | Detection Rate: {:.1}%</p>",
        insert_size.peak(),
        insert_size.mean(),
        insert_size.std_dev(),
        insert_size.detection_rate() * 100.0
    )?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"insertSizeChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    // Get histogram data - only show meaningful range around the peak
    let histogram = insert_size.histogram();
    let peak = insert_size.peak();

    // Determine range to display (peak +/- 200 or valid data range)
    let start = if peak > 200 { peak - 200 } else { 0 };
    let end = (peak + 200).min(histogram.len());

    let labels: Vec<usize> = (start..end).collect();
    let counts: Vec<u64> = histogram[start..end].to_vec();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var trace = {{")?;
    writeln!(writer, "        x: {:?},", labels)?;
    writeln!(writer, "        y: {:?},", counts)?;
    writeln!(writer, "        type: 'bar',")?;
    writeln!(writer, "        name: 'Read Pairs',")?;
    writeln!(writer, "        marker: {{ color: 'rgba(255, 184, 108, 0.7)', line: {{ color: '#ffb86c', width: 1 }} }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Insert Size Distribution', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Insert Size (bp)', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Read Pairs', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        bargap: 0,")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('insertSizeChart', [trace], layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Generate the overrepresented sequences table
fn write_kmer_table<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    let top_seqs = stats.kmer.top_overrepresented();

    // Filter sequences with >= 0.1% frequency
    let significant_seqs: Vec<_> = top_seqs
        .iter()
        .take(10)
        .filter(|(_, count)| {
            if stats.total_reads > 0 {
                (*count as f64 / stats.total_reads as f64) * 100.0 >= 0.1
            } else {
                false
            }
        })
        .collect();

    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Overrepresented Sequences</h2>")?;

    if significant_seqs.is_empty() {
        writeln!(writer, "    <p class=\"no-data\">No overrepresented sequences found (threshold: 0.1%)</p>")?;
    } else {
        writeln!(writer, "    <table class=\"kmer-table\">")?;
        writeln!(writer, "      <thead>")?;
        writeln!(writer, "        <tr>")?;
        writeln!(writer, "          <th>Sequence</th>")?;
        writeln!(writer, "          <th>Count</th>")?;
        writeln!(writer, "          <th>Percentage</th>")?;
        writeln!(writer, "        </tr>")?;
        writeln!(writer, "      </thead>")?;
        writeln!(writer, "      <tbody>")?;

        for (seq, count) in significant_seqs {
            let percentage = (*count as f64 / stats.total_reads as f64) * 100.0;
            let seq_str = String::from_utf8_lossy(seq);
            writeln!(writer, "        <tr>")?;
            writeln!(writer, "          <td class=\"sequence\">{}</td>", seq_str)?;
            writeln!(writer, "          <td>{}</td>", format_number(*count))?;
            writeln!(writer, "          <td>{:.2}%</td>", percentage)?;
            writeln!(writer, "        </tr>")?;
        }

        writeln!(writer, "      </tbody>")?;
        writeln!(writer, "    </table>")?;
    }

    writeln!(writer, "  </div>")?;
    Ok(())
}

/// Generate the quality histogram chart
fn write_quality_histogram<W: Write>(writer: &mut W, stats: &QcStats) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"section\">")?;
    writeln!(writer, "    <h2>Quality Score Histogram</h2>")?;
    writeln!(writer, "    <div class=\"chart-container\">")?;
    writeln!(writer, "      <div id=\"qualHistChart\"></div>")?;
    writeln!(writer, "    </div>")?;
    writeln!(writer, "  </div>")?;

    let hist: Vec<u64> = stats.quality.histogram().to_vec();
    let qual_labels: Vec<u8> = (0..94).collect();

    writeln!(writer, "  <script>")?;
    writeln!(writer, "    (function() {{")?;
    writeln!(writer, "      var trace = {{")?;
    writeln!(writer, "        x: {:?},", qual_labels)?;
    writeln!(writer, "        y: {:?},", hist)?;
    writeln!(writer, "        type: 'bar',")?;
    writeln!(writer, "        name: 'Base Count',")?;
    writeln!(writer, "        marker: {{ color: 'rgba(241, 250, 140, 0.7)', line: {{ color: '#f1fa8c', width: 1 }} }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var layout = {{")?;
    writeln!(writer, "        title: {{ text: 'Quality Score Distribution', font: {{ color: '#f8f8f2', size: 16 }} }},")?;
    writeln!(writer, "        paper_bgcolor: '#44475a',")?;
    writeln!(writer, "        plot_bgcolor: '#282a36',")?;
    writeln!(writer, "        font: {{ color: '#f8f8f2' }},")?;
    writeln!(writer, "        xaxis: {{ title: 'Quality Score', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        yaxis: {{ title: 'Base Count', gridcolor: '#44475a', zerolinecolor: '#44475a' }},")?;
    writeln!(writer, "        bargap: 0.05,")?;
    writeln!(writer, "        margin: {{ t: 50, r: 30, b: 50, l: 60 }}")?;
    writeln!(writer, "      }};")?;
    writeln!(writer, "      var config = {{ responsive: true, scrollZoom: true, displayModeBar: true }};")?;
    writeln!(writer, "      Plotly.newPlot('qualHistChart', [trace], layout, config);")?;
    writeln!(writer, "    }})();")?;
    writeln!(writer, "  </script>")?;
    Ok(())
}

/// Write the footer section
fn write_footer<W: Write>(writer: &mut W) -> anyhow::Result<()> {
    writeln!(writer, "  <div class=\"footer\">")?;
    writeln!(
        writer,
        "    <p>Generated by <strong>Fastars</strong> v{}</p>",
        env!("CARGO_PKG_VERSION")
    )?;
    writeln!(
        writer,
        "    <p>Report generated on {}</p>",
        chrono_lite_now()
    )?;
    writeln!(writer, "  </div>")?;
    writeln!(writer, "</body>")?;
    writeln!(writer, "</html>")?;
    Ok(())
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Format a number with thousand separators
fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.insert(0, ',');
        }
        result.insert(0, c);
    }
    result
}

/// Format base count with appropriate suffix (K, M, G)
fn format_bases(n: u64) -> String {
    if n >= 1_000_000_000 {
        format!("{:.2} Gb", n as f64 / 1_000_000_000.0)
    } else if n >= 1_000_000 {
        format!("{:.2} Mb", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.2} Kb", n as f64 / 1_000.0)
    } else {
        format!("{} bp", n)
    }
}

/// Get a simple timestamp without chrono dependency
fn chrono_lite_now() -> String {
    // Simple timestamp generation without external dependencies
    use std::time::{SystemTime, UNIX_EPOCH};
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();

    // Simple calculation for approximate date/time
    let days_since_epoch = secs / 86400;
    let years = days_since_epoch / 365;
    let year = 1970 + years;

    format!("Year {}", year)
}

// ============================================================================
// Public API
// ============================================================================

/// Generate an HTML report from QC statistics.
pub fn write_html_report<W: Write>(stats: &QcStats, writer: &mut W) -> anyhow::Result<()> {
    let config = HtmlConfig::default();
    write_html_report_with_config(stats, None, &config, writer)
}

/// Generate an HTML report with before/after filtering comparison.
pub fn write_html_report_filtering<W: Write>(
    stats_before: &QcStats,
    stats_after: &QcStats,
    writer: &mut W,
) -> anyhow::Result<()> {
    let config = HtmlConfig::default();
    write_html_report_with_config(stats_before, Some(stats_after), &config, writer)
}

/// Generate an HTML report from FilteringStats.
pub fn write_html_report_from_filtering_stats<W: Write>(
    filtering_stats: &FilteringStats,
    writer: &mut W,
) -> anyhow::Result<()> {
    let config = HtmlConfig::default();
    write_html_report_with_config(
        &filtering_stats.before,
        Some(&filtering_stats.after),
        &config,
        writer,
    )
}

/// Generate an HTML report with configuration options.
pub fn write_html_report_with_config<W: Write>(
    stats_before: &QcStats,
    stats_after: Option<&QcStats>,
    config: &HtmlConfig,
    writer: &mut W,
) -> anyhow::Result<()> {
    // Write HTML head with styles
    write_html_head(writer, config)?;

    // Begin body
    writeln!(writer, "<body>")?;

    // Header
    writeln!(writer, "  <div class=\"header\">")?;
    writeln!(writer, "    <h1>{}</h1>", config.title)?;
    writeln!(writer, "  </div>")?;

    // Main container
    writeln!(writer, "  <div class=\"container\">")?;

    // Summary statistics table
    write_summary_table(writer, stats_before, stats_after)?;

    // Charts section
    writeln!(writer, "    <div class=\"charts-grid\">")?;

    // Quality distribution chart
    write_quality_chart(writer, stats_before, stats_after)?;

    // Base content chart (use after if available, otherwise before)
    let display_stats = stats_after.unwrap_or(stats_before);
    write_base_content_chart(writer, display_stats)?;

    // GC content histogram
    write_gc_chart(writer, display_stats)?;

    // Length distribution
    write_length_chart(writer, display_stats)?;

    // Quality histogram
    write_quality_histogram(writer, display_stats)?;

    // Duplication rate
    write_duplication_chart(writer, display_stats)?;

    // Insert size distribution (only if available)
    write_insert_size_chart(writer, display_stats)?;

    writeln!(writer, "    </div>")?;

    // K-mer overrepresentation table
    write_kmer_table(writer, display_stats)?;

    writeln!(writer, "  </div>")?;

    // Footer
    write_footer(writer)?;

    Ok(())
}

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

    fn create_test_stats() -> QcStats {
        let mut stats = QcStats::new(Mode::Short);
        stats.update_raw(b"ATGCATGC", b"IIIIIIII");
        stats.update_raw(b"GCTAGCTA", b"????????");
        stats.update_raw(b"ATATATATAT", b"5555555555");
        stats
    }

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

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Fastars QC Report"));
        assert!(html.contains("Summary Statistics"));
        assert!(html.contains("Plotly"));
    }

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

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("qualityChart"));
        assert!(html.contains("baseContentChart"));
        assert!(html.contains("gcChart"));
        assert!(html.contains("lengthChart"));
        assert!(html.contains("dupChart"));
    }

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

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Total Reads"));
        assert!(html.contains("Total Bases"));
        assert!(html.contains("Mean Quality"));
        assert!(html.contains("GC Content"));
    }

    #[test]
    fn test_html_report_filtering_comparison() {
        let mut before = QcStats::new(Mode::Short);
        before.update_raw(b"ATGCATGC", b"IIIIIIII");
        before.update_raw(b"LOWQUAL", b"!!!!!!!");

        let mut after = QcStats::new(Mode::Short);
        after.update_raw(b"ATGCATGC", b"IIIIIIII");

        let mut output = Vec::new();
        write_html_report_filtering(&before, &after, &mut output).unwrap();

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Before Filtering"));
        assert!(html.contains("After Filtering"));
    }

    #[test]
    fn test_html_config_custom_title() {
        let stats = create_test_stats();
        let config = HtmlConfig::new().with_title("Custom Report Title");

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

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Custom Report Title"));
    }

    #[test]
    fn test_format_number() {
        assert_eq!(format_number(1234567), "1,234,567");
        assert_eq!(format_number(1000), "1,000");
        assert_eq!(format_number(999), "999");
        assert_eq!(format_number(0), "0");
    }

    #[test]
    fn test_format_bases() {
        assert!(format_bases(1_500_000_000).contains("Gb"));
        assert!(format_bases(1_500_000).contains("Mb"));
        assert!(format_bases(1_500).contains("Kb"));
        assert!(format_bases(500).contains("bp"));
    }

    #[test]
    fn test_html_report_from_filtering_stats() {
        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_html_report_from_filtering_stats(&filtering_stats, &mut output).unwrap();

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Before Filtering"));
        assert!(html.contains("After Filtering"));
    }

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

        let html = String::from_utf8(output).unwrap();
        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("<html"));
        assert!(html.contains("</html>"));
        assert!(html.contains("<head>"));
        assert!(html.contains("</head>"));
        assert!(html.contains("<body>"));
        assert!(html.contains("</body>"));
    }

    #[test]
    fn test_empty_stats_report() {
        let stats = QcStats::new(Mode::Short);
        let mut output = Vec::new();
        write_html_report(&stats, &mut output).unwrap();

        let html = String::from_utf8(output).unwrap();
        assert!(html.contains("Fastars QC Report"));
        // Should not crash with empty stats
    }
}