fastdedup 1.2.0

A fast and memory-efficient FASTX PCR deduplication tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
use assert_cmd::cargo;
use assert_cmd::Command;
use assert_fs::prelude::*;
use predicates::prelude::*;
use std::fs;
use std::fs::File;
use std::io::Write;
use flate2::write::GzEncoder;
use flate2::Compression;

// ================================================================
// UTILITAIRE : BUILDER DE COMMANDE
// ================================================================

fn cmd() -> Command {
    cargo::cargo_bin_cmd!("fdedup")
}

// ================================================================
// UTILITAIRE : GÉNÉRATION DE SÉQUENCES
// ================================================================

/// Génère une séquence ACGT déterministe de 150 bases via LCG.
///
/// Remplace l'encodage en base 5 précédent :
///   - N'utilise que ACGT (pas de N, conforme NovaSeq haute qualité)
///   - Distribution équilibrée (~25% par base) pour toutes les plages d'indices
///   - Garantit l'unicité en pratique pour tous les indices utilisés dans les tests
///     (max ~200 ; probabilité de collision dans 4^150 séquences ≈ 0)
///
/// Convention d'offset :
///   offset = 0    → séquences R1 / Single-End
///   offset = 9999 → séquences R2 (distinctes pour le même index)
fn generer_sequence(index: usize, offset: usize) -> String {
    const LONGUEUR: usize = 150;
    const NUCLEOTIDES: [u8; 4] = [b'A', b'C', b'G', b'T'];
    // Graine dérivée de (index, offset) ; +1 pour éviter l'état nul
    let mut state = index
        .wrapping_mul(2_654_435_761)
        .wrapping_add(offset.wrapping_mul(40_503))
        .wrapping_add(1) as u64;
    let mut seq = Vec::with_capacity(LONGUEUR);
    for _ in 0..LONGUEUR {
        // LCG de Knuth (période maximale sur u64)
        state = state
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        seq.push(NUCLEOTIDES[((state >> 33) & 3) as usize]);
    }
    String::from_utf8(seq).expect("Séquence UTF-8 invalide")
}

/// Génère des scores de qualité NovaSeq réalistes sur 150 cycles.
///
/// NovaSeq utilise exclusivement 4 bins de qualité :
///   Q2  → '#' (ASCII 35) — bases très basses qualité
///   Q12 → '-' (ASCII 45) — bases dégradées
///   Q23 → '8' (ASCII 56) — qualité intermédiaire
///   Q37 → 'F' (ASCII 70) — haute qualité (majorité)
///
/// Distribution approximative : 5% Q2, 5% Q12, 15% Q23, 75% Q37
/// (profil typique de lecture NovaSeq 2×150 sur génome entier).
fn generer_qualite(index: usize) -> String {
    const BINS: [u8; 4] = [b'#', b'-', b'8', b'F'];
    let mut state = index.wrapping_mul(2_654_435_761).wrapping_add(99_991) as u64;
    let mut qual = Vec::with_capacity(150);
    for _ in 0..150 {
        state = state
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        let r = (state >> 33) % 100;
        let bin = if r < 5 { 0 } else if r < 10 { 1 } else if r < 25 { 2 } else { 3 };
        qual.push(BINS[bin]);
    }
    String::from_utf8(qual).unwrap()
}

// ================================================================
// UTILITAIRE : GÉNÉRATEURS DE FICHIERS
// ================================================================

fn generer_fastq(
    dir: &assert_fs::TempDir,
    nom_fichier: &str,
    nb_uniques: usize,
    nb_duplications: usize,
) -> assert_fs::fixture::ChildPath {
    let fichier = dir.child(nom_fichier);
    let mut contenu = String::new();

    for i in 0..nb_uniques {
        contenu.push_str(&format!(
            "@A00123:456:HFWV2DSXX:1:1101:1000:{} 1:N:0:ATGC\n{}\n+\n{}\n",
            1000 + i,
            generer_sequence(i, 0),
            generer_qualite(i)
        ));
    }
    for i in 0..nb_duplications {
        // Même séquence qu'à l'index i, qualité différente (duplication PCR réaliste)
        contenu.push_str(&format!(
            "@A00123:456:HFWV2DSXX:1:1101:5000:{} 1:N:0:ATGC\n{}\n+\n{}\n",
            1000 + i,
            generer_sequence(i, 0),
            generer_qualite(i + 1000)
        ));
    }

    fichier.write_str(&contenu).unwrap();
    fichier
}

/// Crée un fichier FASTQ compressé (.fastq.gz) utilisable comme entrée.
fn generer_fastq_gz(
    dir: &assert_fs::TempDir,
    nom_fichier: &str,
    nb_uniques: usize,
    nb_duplications: usize,
) -> assert_fs::fixture::ChildPath {
    let fichier = dir.child(nom_fichier);
    let mut contenu = String::new();

    for i in 0..nb_uniques {
        contenu.push_str(&format!(
            "@A00123:456:HFWV2DSXX:1:1101:1000:{} 1:N:0:ATGC\n{}\n+\n{}\n",
            1000 + i,
            generer_sequence(i, 0),
            generer_qualite(i)
        ));
    }
    for i in 0..nb_duplications {
        contenu.push_str(&format!(
            "@A00123:456:HFWV2DSXX:1:1101:5000:{} 1:N:0:ATGC\n{}\n+\n{}\n",
            1000 + i,
            generer_sequence(i, 0),
            generer_qualite(i + 1000)
        ));
    }

    let file = File::create(fichier.path()).unwrap();
    let mut encoder = GzEncoder::new(file, Compression::default());
    encoder.write_all(contenu.as_bytes()).unwrap();
    encoder.finish().unwrap();
    fichier
}

fn generer_fasta(
    dir: &assert_fs::TempDir,
    nom_fichier: &str,
    nb_uniques: usize,
    nb_duplications: usize,
) -> assert_fs::fixture::ChildPath {
    let fichier = dir.child(nom_fichier);
    let mut contenu = String::new();

    for i in 0..nb_uniques {
        contenu.push_str(&format!(
            ">A00123:456:HFWV2DSXX:1:1101:1000:{} 1:N:0:ATGC\n{}\n",
            1000 + i,
            generer_sequence(i, 0)
        ));
    }
    for i in 0..nb_duplications {
        contenu.push_str(&format!(
            ">A00123:456:HFWV2DSXX:1:1101:5000:{} 1:N:0:ATGC\n{}\n",
            1000 + i,
            generer_sequence(i, 0)
        ));
    }

    fichier.write_str(&contenu).unwrap();
    fichier
}

fn generer_fastq_paire(
    dir: &assert_fs::TempDir,
    nom_r1: &str,
    nom_r2: &str,
    nb_uniques: usize,
    nb_duplications: usize,
) -> (assert_fs::fixture::ChildPath, assert_fs::fixture::ChildPath) {
    let fichier_r1 = dir.child(nom_r1);
    let fichier_r2 = dir.child(nom_r2);
    let mut contenu_r1 = String::new();
    let mut contenu_r2 = String::new();

    for i in 0..nb_uniques {
        // L'ID de base est identique pour R1 et R2 ; seul le champ direction (1: vs 2:) diffère.
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:1000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            "@{} 1:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 0),
            generer_qualite(i)
        ));
        contenu_r2.push_str(&format!(
            "@{} 2:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 9999),
            generer_qualite(i + 500)
        ));
    }
    for i in 0..nb_duplications {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:5000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            "@{} 1:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 0),
            generer_qualite(i + 1000)
        ));
        contenu_r2.push_str(&format!(
            "@{} 2:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 9999),
            generer_qualite(i + 1500)
        ));
    }

    fichier_r1.write_str(&contenu_r1).unwrap();
    fichier_r2.write_str(&contenu_r2).unwrap();
    (fichier_r1, fichier_r2)
}

fn generer_fasta_paire(
    dir: &assert_fs::TempDir,
    nom_r1: &str,
    nom_r2: &str,
    nb_uniques: usize,
    nb_duplications: usize,
) -> (assert_fs::fixture::ChildPath, assert_fs::fixture::ChildPath) {
    let fichier_r1 = dir.child(nom_r1);
    let fichier_r2 = dir.child(nom_r2);
    let mut contenu_r1 = String::new();
    let mut contenu_r2 = String::new();

    for i in 0..nb_uniques {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:1000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            ">{} 1:N:0:ATGC\n{}\n",
            base_cluster,
            generer_sequence(i, 0)
        ));
        contenu_r2.push_str(&format!(
            ">{} 2:N:0:ATGC\n{}\n",
            base_cluster,
            generer_sequence(i, 9999)
        ));
    }
    for i in 0..nb_duplications {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:5000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            ">{} 1:N:0:ATGC\n{}\n",
            base_cluster,
            generer_sequence(i, 0)
        ));
        contenu_r2.push_str(&format!(
            ">{} 2:N:0:ATGC\n{}\n",
            base_cluster,
            generer_sequence(i, 9999)
        ));
    }

    fichier_r1.write_str(&contenu_r1).unwrap();
    fichier_r2.write_str(&contenu_r2).unwrap();
    (fichier_r1, fichier_r2)
}

/// Génère une paire de fichiers FASTQ avec un nombre de reads délibérément
/// différent entre R1 et R2, pour tester la détection de désynchronisation
/// en fin de fichier.
fn generer_fastq_paire_desynchronisee(
    dir: &assert_fs::TempDir,
    nom_r1: &str,
    nom_r2: &str,
    nb_r1: usize,
    nb_r2: usize,
) -> (assert_fs::fixture::ChildPath, assert_fs::fixture::ChildPath) {
    let fichier_r1 = dir.child(nom_r1);
    let fichier_r2 = dir.child(nom_r2);
    let mut contenu_r1 = String::new();
    let mut contenu_r2 = String::new();

    // Portion commune : IDs identiques, boucle synchronisée
    let nb_common = nb_r1.min(nb_r2);
    for i in 0..nb_common {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:1000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            "@{} 1:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 0),
            generer_qualite(i)
        ));
        contenu_r2.push_str(&format!(
            "@{} 2:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 9999),
            generer_qualite(i + 500)
        ));
    }
    // Reads supplémentaires côté R1 (si R1 > R2)
    for i in nb_common..nb_r1 {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:1000:{}", 1000 + i);
        contenu_r1.push_str(&format!(
            "@{} 1:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 0),
            generer_qualite(i)
        ));
    }
    // Reads supplémentaires côté R2 (si R2 > R1)
    for i in nb_common..nb_r2 {
        let base_cluster = format!("A00123:456:HFWV2DSXX:1:1101:1000:{}", 1000 + i);
        contenu_r2.push_str(&format!(
            "@{} 2:N:0:ATGC\n{}\n+\n{}\n",
            base_cluster,
            generer_sequence(i, 9999),
            generer_qualite(i + 500)
        ));
    }

    fichier_r1.write_str(&contenu_r1).unwrap();
    fichier_r2.write_str(&contenu_r2).unwrap();
    (fichier_r1, fichier_r2)
}

// ================================================================
// UTILITAIRE : HELPERS D'ANALYSE DE SORTIE
// ================================================================

fn decompresser_gz(chemin: &std::path::Path) -> String {
    let octets = fs::read(chemin).unwrap();
    let mut decoder = flate2::read::GzDecoder::new(&octets[..]);
    let mut contenu = String::new();
    std::io::Read::read_to_string(&mut decoder, &mut contenu).unwrap();
    contenu
}

fn compter_sequences_fastq(contenu: &str) -> usize {
    contenu.lines().filter(|l| l.starts_with('@')).count()
}

fn compter_sequences_fasta(contenu: &str) -> usize {
    contenu.lines().filter(|l| l.starts_with('>')).count()
}

/// Extrait la liste des identifiants de base (avant l'espace) depuis un contenu FASTQ.
/// Permet une vérification de contenu, pas seulement de compte.
fn extraire_ids_fastq(contenu: &str) -> Vec<String> {
    contenu
        .lines()
        .filter(|l| l.starts_with('@'))
        .map(|l| {
            l.trim_start_matches('@')
                .split_whitespace()
                .next()
                .unwrap_or(l)
                .to_string()
        })
        .collect()
}

// ================================================================
// TESTS SINGLE-END — ERREURS D'ENTRÉE
// ================================================================

#[test]
fn test_fichier_entree_inexistant() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    cmd()
        .current_dir(temp_dir.path())
        .arg("-1").arg("fichier_fantome.fastq")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Input file not found"));
}

/// Ne teste pas de chaîne exacte issue de needletail (fragile aux mises à jour
/// de la bibliothèque) — seul l'échec est vérifié.
#[test]
fn test_fichier_entree_vide() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let fichier_vide = temp_dir.child("vide.fastq");
    fichier_vide.touch().unwrap();
    cmd()
        .arg("-1").arg(fichier_vide.path())
        .arg("-s")
        .assert()
        .failure();
}

#[test]
fn test_fichier_entree_mauvais_format() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let fichier_texte = temp_dir.child("mauvais_format.txt");
    fichier_texte
        .write_str("Ceci n'est pas un fichier FASTQ\nAvec plusieurs lignes.")
        .unwrap();
    cmd()
        .arg("-1").arg(fichier_texte.path())
        .arg("-s")
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("Invalid sequence data")
                .or(predicate::str::contains("Failed to read input file")),
        );
}

#[test]
fn test_fichier_sortie_chemin_inexistant() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let fichier_entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    cmd()
        .arg("-1").arg(fichier_entree.path())
        .arg("-o").arg("/chemin/vers/un/dossier/inexistant/sortie.fastq")
        .assert()
        .failure();
}

#[test]
fn test_fichier_sortie_gz_corrompu() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let fichier_entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    let fichier_sortie_corrompu = temp_dir.child("sortie_corrompue.fastq.gz");
    fichier_sortie_corrompu
        .write_str("Ceci n'est pas un gzip valide.")
        .unwrap();
    cmd()
        .arg("-1").arg(fichier_entree.path())
        .arg("-o").arg(fichier_sortie_corrompu.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error opening preload file"));
}

// ================================================================
// TESTS SINGLE-END — TAUX DE DUPLICATION
// ================================================================

#[test]
fn test_taux_duplication_zero_pourcent() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "100_uniques.fastq", 100, 0);
    cmd()
        .arg("-1").arg(entree.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 100"))
        .stdout(predicate::str::contains("Duplicates removed: 0.00%"));
}

#[test]
fn test_taux_duplication_9_09_pourcent() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // 100 uniques + 10 duplicats = 110 lectures, 10/110 ≈ 9.09%
    let entree = generer_fastq(&temp_dir, "110_seq.fastq", 100, 10);
    cmd()
        .arg("-1").arg(entree.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 110"))
        .stdout(predicate::str::contains("Duplicates removed: 9.09%"));
}

#[test]
fn test_taux_duplication_50_pourcent() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // 10 uniques + 10 duplicats = 20 lectures, 10/20 = 50.00%
    let entree = generer_fastq(&temp_dir, "50_pourcent.fastq", 10, 10);
    cmd()
        .arg("-1").arg(entree.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 20"))
        .stdout(predicate::str::contains("Duplicates removed: 50.00%"));
}

/// Taux de duplication typique NovaSeq sur librairie amplicon/faible-input (~30%).
#[test]
fn test_taux_duplication_30_pourcent_novaseq() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // 70 uniques + 30 duplicats = 100 lectures, 30/100 = 30.00%
    let entree = generer_fastq(&temp_dir, "30_pourcent.fastq", 70, 30);
    cmd()
        .arg("-1").arg(entree.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 100"))
        .stdout(predicate::str::contains("Duplicates removed: 30.00%"));
}

#[test]
fn test_taux_duplication_entree_toutes_identiques() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // 10 lectures identiques : 1 unique + 9 doublons = 90.00%
    let fichier = temp_dir.child("tous_identiques.fastq");
    let seq = generer_sequence(42, 0);
    let mut contenu = String::new();
    for i in 0..10 {
        contenu.push_str(&format!(
            "@read_{} 1:N:0:ATGC\n{}\n+\n{}\n",
            i, seq, generer_qualite(i)
        ));
    }
    fichier.write_str(&contenu).unwrap();

    cmd()
        .arg("-1").arg(fichier.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 10"))
        .stdout(predicate::str::contains("Duplicates removed: 90.00%"));
}

// ================================================================
// TESTS SINGLE-END — ENTRÉE COMPRESSÉE (GZ)
// ================================================================

/// Vérifie que needletail lit correctement un fichier .fastq.gz en entrée.
#[test]
fn test_entree_fastq_gz_compresse() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq_gz(&temp_dir, "entree.fastq.gz", 20, 5);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert_eq!(
        compter_sequences_fastq(&contenu),
        20,
        "Doit contenir 20 séquences uniques depuis une entrée .fastq.gz"
    );
}

/// Vérifie le taux de duplication en dry-run sur une entrée .fastq.gz.
/// 50 uniques + 10 duplicats = 60 lectures, 10/60 ≈ 16.67%
#[test]
fn test_entree_fastq_gz_dry_run() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq_gz(&temp_dir, "entree.fastq.gz", 50, 10);

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Processed fragments: 60"))
        .stdout(predicate::str::contains("Duplicates removed: 16.67%"));
}

// ================================================================
// TESTS SINGLE-END — FORMAT ET COMPRESSION DE SORTIE
// ================================================================

#[test]
fn test_sortie_fastq_non_compresse() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('@'), "La sortie FASTQ doit commencer par '@'");
    assert!(contenu.contains('+'), "La sortie FASTQ doit contenir la ligne '+'");
    assert_eq!(compter_sequences_fastq(&contenu), 10);
}

#[test]
fn test_sortie_fastq_gz_compresse() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 3);
    let sortie = temp_dir.child("sortie.fastq.gz");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let octets = fs::read(sortie.path()).unwrap();
    assert_eq!(octets[0], 0x1f, "Magic byte gzip attendu");
    assert_eq!(octets[1], 0x8b, "Magic byte gzip attendu");

    let contenu = decompresser_gz(sortie.path());
    assert!(contenu.starts_with('@'));
    assert_eq!(compter_sequences_fastq(&contenu), 10);
}

#[test]
fn test_sortie_fq_extension() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 5, 0);
    let sortie = temp_dir.child("sortie.fq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('@'), "L'extension .fq doit produire du FASTQ");
    assert_eq!(compter_sequences_fastq(&contenu), 5);
}

#[test]
fn test_sortie_fq_gz_compresse() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 5, 0);
    let sortie = temp_dir.child("sortie.fq.gz");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let octets = fs::read(sortie.path()).unwrap();
    assert_eq!(octets[0], 0x1f);
    assert_eq!(octets[1], 0x8b);

    let contenu = decompresser_gz(sortie.path());
    assert_eq!(compter_sequences_fastq(&contenu), 5);
}

#[test]
fn test_sortie_fasta_extension_fasta() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 2);
    let sortie = temp_dir.child("sortie.fasta");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('>'), "La sortie .fasta doit commencer par '>'");
    assert!(!contenu.contains('+'), "La sortie FASTA ne doit pas contenir de ligne '+'");
    assert_eq!(compter_sequences_fasta(&contenu), 10);
}

#[test]
fn test_sortie_fasta_extension_fa() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 7, 0);
    let sortie = temp_dir.child("sortie.fa");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('>'), "L'extension .fa doit produire du FASTA");
    assert_eq!(compter_sequences_fasta(&contenu), 7);
}

#[test]
fn test_sortie_fasta_extension_fna() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 7, 0);
    let sortie = temp_dir.child("sortie.fna");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('>'), "L'extension .fna doit produire du FASTA");
    assert_eq!(compter_sequences_fasta(&contenu), 7);
}

#[test]
fn test_sortie_fasta_gz_compresse() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 8, 2);
    let sortie = temp_dir.child("sortie.fasta.gz");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let octets = fs::read(sortie.path()).unwrap();
    assert_eq!(octets[0], 0x1f);
    assert_eq!(octets[1], 0x8b);

    let contenu = decompresser_gz(sortie.path());
    assert!(contenu.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu), 8);
}

#[test]
fn test_entree_fasta_sortie_fasta() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fasta(&temp_dir, "entree.fasta", 10, 3);
    let sortie = temp_dir.child("sortie.fasta");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = fs::read_to_string(sortie.path()).unwrap();
    assert!(contenu.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu), 10);
}

/// La conversion FASTA → FASTQ est impossible (pas de scores de qualité en FASTA).
/// Le binaire doit refuser explicitement cette opération.
#[test]
fn test_entree_fasta_sortie_fastq_non_supporte() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fasta(&temp_dir, "entree.fasta", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("FASTA → FASTQ conversion not supported"));
}

// ================================================================
// TESTS SINGLE-END — COMPORTEMENT --force ET REPRISE
// ================================================================

#[test]
fn test_force_overwrites_existing_file() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree_1 = generer_fastq(&temp_dir, "entree_1.fastq", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree_1.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie.path()).unwrap()),
        10
    );

    // Second passage avec --force et un fichier plus petit : doit écraser, pas ajouter
    let entree_2 = generer_fastq(&temp_dir, "entree_2.fastq", 4, 0);
    cmd()
        .arg("-1").arg(entree_2.path())
        .arg("-o").arg(sortie.path())
        .arg("--force")
        .assert()
        .success();

    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie.path()).unwrap()),
        4,
        "--force doit écraser le fichier existant, pas y ajouter"
    );
}

#[test]
fn test_without_force_resumes_from_existing_output() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree_initiale = generer_fastq(&temp_dir, "entree_initiale.fastq", 5, 0);
    let sortie = temp_dir.child("sortie_reprise.fastq");

    // Premier passage : 5 séquences uniques
    cmd()
        .arg("-1").arg(entree_initiale.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    // Deuxième passage : les 5 mêmes + 5 nouvelles
    let entree_complete = generer_fastq(&temp_dir, "entree_complete.fastq", 10, 0);
    cmd()
        .arg("-1").arg(entree_complete.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu_final = fs::read_to_string(sortie.path()).unwrap();
    assert_eq!(
        compter_sequences_fastq(&contenu_final),
        10,
        "Après reprise, la sortie doit contenir 10 séquences uniques au total"
    );

    // Vérification de contenu : aucun ID ne doit apparaître deux fois
    let ids = extraire_ids_fastq(&contenu_final);
    let mut ids_tries = ids.clone();
    ids_tries.sort();
    ids_tries.dedup();
    assert_eq!(
        ids.len(),
        ids_tries.len(),
        "Aucun ID de lecture ne doit être dupliqué dans la sortie de reprise"
    );
}

// ================================================================
// TESTS SINGLE-END — SÉLECTION AUTOMATIQUE DU MODE DE HACHAGE
// ================================================================

/// Un threshold très petit (→ 0) force la sélection du 128-bit pour toute taille de fichier.
/// Vérifie le chemin de sélection automatique sans nécessiter un fichier de 67 Go.
#[test]
fn test_selection_automatique_hash_128_bits_via_threshold() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .arg("-t").arg("0.000000000000000000001") // threshold ≈ 0 → seuil = ~0 → 128-bit
        .arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("128-bit Hash"));
}

/// Un threshold de 1.0 (100% de collisions acceptées) force le 64-bit pour toute taille pratique.
#[test]
fn test_selection_automatique_hash_64_bits_via_threshold() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .arg("-t").arg("1.0") // seuil ≈ 6 milliards → fichiers de test bien en dessous
        .arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("64-bit Hash"));
}

/// Vérifie que l'avertissement est émis quand --hash et --threshold sont fournis ensemble.
#[test]
fn test_avertissement_hash_et_threshold_ignores() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 0);
    let sortie = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .arg("-H").arg("64")
        .arg("-t").arg("0.5")
        .assert()
        .success()
        .stderr(
            predicate::str::contains("threshold")
                .and(predicate::str::contains("ignored")),
        );
}

// ================================================================
// TESTS SINGLE-END — MODE DE HACHAGE MANUEL
// ================================================================

#[test]
fn test_hachage_64_bits_explicite() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 20, 5);
    let sortie = temp_dir.child("sortie_64.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .arg("-H").arg("64")
        .arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("64-bit Hash"));

    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie.path()).unwrap()),
        20
    );
}

#[test]
fn test_hachage_128_bits_explicite() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 20, 5);
    let sortie = temp_dir.child("sortie_128.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .arg("-H").arg("128")
        .arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("128-bit Hash"));

    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie.path()).unwrap()),
        20
    );
}

#[test]
fn test_hachage_64_et_128_bits_produisent_le_meme_resultat() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 15, 5);
    let sortie_64 = temp_dir.child("sortie_64.fastq");
    let sortie_128 = temp_dir.child("sortie_128.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie_64.path())
        .arg("-H").arg("64")
        .assert()
        .success();

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie_128.path())
        .arg("-H").arg("128")
        .assert()
        .success();

    let count_64 = compter_sequences_fastq(&fs::read_to_string(sortie_64.path()).unwrap());
    let count_128 = compter_sequences_fastq(&fs::read_to_string(sortie_128.path()).unwrap());
    assert_eq!(
        count_64, count_128,
        "Les deux modes de hachage doivent produire le même nombre de séquences uniques"
    );
}

// ================================================================
// TESTS SINGLE-END — INTÉGRITÉ APRÈS COMPRESSION
// ================================================================

#[test]
fn test_compression_gz_valide_fastq() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 50, 10);
    let sortie = temp_dir.child("sortie.fastq.gz");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = decompresser_gz(sortie.path());
    assert!(contenu.starts_with('@'));
    assert_eq!(compter_sequences_fastq(&contenu), 50);
}

#[test]
fn test_compression_gz_valide_fasta() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 50, 10);
    let sortie = temp_dir.child("sortie.fasta.gz");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie.path())
        .assert()
        .success();

    let contenu = decompresser_gz(sortie.path());
    assert!(contenu.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu), 50);
}

#[test]
fn test_deduplication_preservee_apres_compression() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let entree = generer_fastq(&temp_dir, "entree.fastq", 10, 10);
    let sortie_gz = temp_dir.child("sortie.fastq.gz");
    let sortie_non_gz = temp_dir.child("sortie.fastq");

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie_gz.path())
        .assert()
        .success();

    cmd()
        .arg("-1").arg(entree.path())
        .arg("-o").arg(sortie_non_gz.path())
        .arg("--force")
        .assert()
        .success();

    let count_gz = compter_sequences_fastq(&decompresser_gz(sortie_gz.path()));
    let count_non_gz =
        compter_sequences_fastq(&fs::read_to_string(sortie_non_gz.path()).unwrap());

    assert_eq!(
        count_gz, count_non_gz,
        "Le nombre de séquences doit être identique entre .gz et non-.gz"
    );
    assert_eq!(count_gz, 10, "Doit contenir exactement 10 séquences uniques");
}

// ================================================================
// TESTS PAIRED-END — ERREURS ET VALIDATION
// ================================================================

#[test]
fn test_paire_erreur_sortie_r2_manquante() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 0);
    let sortie_r1 = temp_dir.child("sortie_r1.fastq");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        // -p intentionnellement absent
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("--output-r2")
                .and(predicate::str::contains("required")),
        );
}

#[test]
fn test_paire_desynchronisee_en_tete_bloquee() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1_desync.fastq", "R2_desync.fastq", 10, 0);

    // Insérer une lecture en tête de R2 : l'ID du premier record R2 ne correspond plus à R1
    let mut contenu_r2_corrompu = String::from(
        "@A00123:456:HFWV2DSXX:1:1101:9999:9999 2:N:0:ATGC\nATGC\n+\nFFFF\n",
    );
    contenu_r2_corrompu.push_str(&fs::read_to_string(r2.path()).unwrap());
    r2.write_str(&contenu_r2_corrompu).unwrap();

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-p").arg(temp_dir.child("dummy_r2.fastq").path())
        .arg("-s")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Critical desynchronization detected"));
}

/// Vérifie la détection de désynchronisation de fin de fichier quand R1 > R2.
#[test]
fn test_paire_desync_fin_fichier_r1_plus_long() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // R1 : 12 reads, R2 : 10 reads — les 10 premiers s'apparient correctement
    let (r1, r2) =
        generer_fastq_paire_desynchronisee(&temp_dir, "R1.fastq", "R2.fastq", 12, 10);

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(temp_dir.child("out_r1.fastq").path())
        .arg("-p").arg(temp_dir.child("out_r2.fastq").path())
        .arg("--force")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Desynchronization detected at the end"));
}

/// Vérifie la détection de désynchronisation de fin de fichier quand R2 > R1.
#[test]
fn test_paire_desync_fin_fichier_r2_plus_long() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // R1 : 10 reads, R2 : 12 reads
    let (r1, r2) =
        generer_fastq_paire_desynchronisee(&temp_dir, "R1.fastq", "R2.fastq", 10, 12);

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(temp_dir.child("out_r1.fastq").path())
        .arg("-p").arg(temp_dir.child("out_r2.fastq").path())
        .arg("--force")
        .assert()
        .failure()
        .stderr(predicate::str::contains("Desynchronization detected at the end"));
}

#[test]
fn test_paire_formats_incoherents() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 0);

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(temp_dir.child("sortie_R1.fasta").path())
        .arg("-p").arg(temp_dir.child("sortie_R2.fastq").path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("must have the same format"));
}

/// La conversion FASTA → FASTQ doit être bloquée en mode Paired-End.
#[test]
fn test_paire_entree_fasta_sortie_fastq_non_supporte() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fasta_paire(&temp_dir, "R1.fasta", "R2.fasta", 10, 0);

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(temp_dir.child("sortie_R1.fastq").path())
        .arg("-p").arg(temp_dir.child("sortie_R2.fastq").path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("FASTA → FASTQ conversion not supported"));
}

// ================================================================
// TESTS PAIRED-END — TAUX DE DUPLICATION
// ================================================================

#[test]
fn test_paire_taux_duplication_33_pourcent() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    // 100 paires uniques + 50 dupliquées = 150 paires, 50/150 ≈ 33.33%
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 100, 50);

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-p").arg(temp_dir.child("dummy_r2.fastq").path())
        .arg("-s").arg("-v")
        .assert()
        .success()
        .stdout(predicate::str::contains("Paired-End"))
        .stdout(predicate::str::contains("Processed fragments: 150"))
        .stdout(predicate::str::contains("Duplicates removed: 33.33%"));
}

// ================================================================
// TESTS PAIRED-END — FORMAT ET COMPRESSION DE SORTIE
// ================================================================

#[test]
fn test_paire_sortie_fastq() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 3);
    let sortie_r1 = temp_dir.child("sortie_R1.fastq");
    let sortie_r2 = temp_dir.child("sortie_R2.fastq");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let contenu_r1 = fs::read_to_string(sortie_r1.path()).unwrap();
    let contenu_r2 = fs::read_to_string(sortie_r2.path()).unwrap();

    assert!(contenu_r1.starts_with('@'));
    assert!(contenu_r2.starts_with('@'));
    assert_eq!(compter_sequences_fastq(&contenu_r1), 10, "R1 doit contenir 10 paires uniques");
    assert_eq!(compter_sequences_fastq(&contenu_r2), 10, "R2 doit contenir 10 paires uniques");
    assert_eq!(
        compter_sequences_fastq(&contenu_r1),
        compter_sequences_fastq(&contenu_r2),
        "R1 et R2 doivent être synchronisés"
    );
}

#[test]
fn test_paire_sortie_fasta() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 3);
    let sortie_r1 = temp_dir.child("sortie_R1.fasta");
    let sortie_r2 = temp_dir.child("sortie_R2.fasta");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let contenu_r1 = fs::read_to_string(sortie_r1.path()).unwrap();
    let contenu_r2 = fs::read_to_string(sortie_r2.path()).unwrap();

    assert!(contenu_r1.starts_with('>'));
    assert!(contenu_r2.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu_r1), 10);
    assert_eq!(compter_sequences_fasta(&contenu_r2), 10);
}

#[test]
fn test_paire_sortie_fastq_gz() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 3);
    let sortie_r1 = temp_dir.child("sortie_R1.fastq.gz");
    let sortie_r2 = temp_dir.child("sortie_R2.fastq.gz");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    for sortie in [&sortie_r1, &sortie_r2] {
        let octets = fs::read(sortie.path()).unwrap();
        assert_eq!(octets[0], 0x1f);
        assert_eq!(octets[1], 0x8b);
    }

    let contenu_r1 = decompresser_gz(sortie_r1.path());
    let contenu_r2 = decompresser_gz(sortie_r2.path());

    assert!(contenu_r1.starts_with('@'));
    assert_eq!(compter_sequences_fastq(&contenu_r1), 10);
    assert_eq!(
        compter_sequences_fastq(&contenu_r1),
        compter_sequences_fastq(&contenu_r2)
    );
}

#[test]
fn test_paire_sortie_fasta_gz() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fastq_paire(&temp_dir, "R1.fastq", "R2.fastq", 10, 3);
    let sortie_r1 = temp_dir.child("sortie_R1.fasta.gz");
    let sortie_r2 = temp_dir.child("sortie_R2.fasta.gz");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    for sortie in [&sortie_r1, &sortie_r2] {
        let octets = fs::read(sortie.path()).unwrap();
        assert_eq!(octets[0], 0x1f);
        assert_eq!(octets[1], 0x8b);
    }

    let contenu_r1 = decompresser_gz(sortie_r1.path());
    let contenu_r2 = decompresser_gz(sortie_r2.path());

    assert!(contenu_r1.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu_r1), 10);
    assert_eq!(
        compter_sequences_fasta(&contenu_r1),
        compter_sequences_fasta(&contenu_r2)
    );
}

#[test]
fn test_paire_entree_fasta_sortie_fasta() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let (r1, r2) = generer_fasta_paire(&temp_dir, "R1.fasta", "R2.fasta", 10, 3);
    let sortie_r1 = temp_dir.child("sortie_R1.fasta");
    let sortie_r2 = temp_dir.child("sortie_R2.fasta");

    cmd()
        .arg("-1").arg(r1.path())
        .arg("-2").arg(r2.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let contenu_r1 = fs::read_to_string(sortie_r1.path()).unwrap();
    let contenu_r2 = fs::read_to_string(sortie_r2.path()).unwrap();

    assert!(contenu_r1.starts_with('>'));
    assert!(contenu_r2.starts_with('>'));
    assert_eq!(compter_sequences_fasta(&contenu_r1), 10);
    assert_eq!(
        compter_sequences_fasta(&contenu_r1),
        compter_sequences_fasta(&contenu_r2)
    );
}

// ================================================================
// TESTS PAIRED-END — REPRISE (RESUME)
// ================================================================

/// Vérifie que la reprise sans --force fonctionne en mode paired-end :
/// après le second passage, R1 et R2 doivent contenir exactement le total
/// de paires uniques sans duplication de contenu.
#[test]
fn test_paire_reprise_depuis_sortie_existante() {
    let temp_dir = assert_fs::TempDir::new().unwrap();

    // Premier passage : 5 paires uniques
    let (r1_init, r2_init) =
        generer_fastq_paire(&temp_dir, "R1_init.fastq", "R2_init.fastq", 5, 0);
    let sortie_r1 = temp_dir.child("sortie_R1.fastq");
    let sortie_r2 = temp_dir.child("sortie_R2.fastq");

    cmd()
        .arg("-1").arg(r1_init.path())
        .arg("-2").arg(r2_init.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie_r1.path()).unwrap()),
        5
    );
    assert_eq!(
        compter_sequences_fastq(&fs::read_to_string(sortie_r2.path()).unwrap()),
        5
    );

    // Deuxième passage : 5 mêmes paires + 5 nouvelles, sans --force
    let (r1_full, r2_full) =
        generer_fastq_paire(&temp_dir, "R1_full.fastq", "R2_full.fastq", 10, 0);

    cmd()
        .arg("-1").arg(r1_full.path())
        .arg("-2").arg(r2_full.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let final_r1 = fs::read_to_string(sortie_r1.path()).unwrap();
    let final_r2 = fs::read_to_string(sortie_r2.path()).unwrap();

    assert_eq!(
        compter_sequences_fastq(&final_r1),
        10,
        "R1 doit contenir 10 paires uniques après la reprise"
    );
    assert_eq!(
        compter_sequences_fastq(&final_r2),
        10,
        "R2 doit contenir 10 paires uniques après la reprise"
    );
    assert_eq!(
        compter_sequences_fastq(&final_r1),
        compter_sequences_fastq(&final_r2),
        "R1 et R2 doivent rester synchronisés après la reprise"
    );
}

/// Vérifie que la synchronisation R1/R2 est préservée après une reprise :
/// le read à la position N dans R1 et le read à la position N dans R2
/// doivent avoir le même identifiant de cluster.
#[test]
fn test_paire_reprise_synchronisation_r1_r2() {
    let temp_dir = assert_fs::TempDir::new().unwrap();

    let (r1_init, r2_init) =
        generer_fastq_paire(&temp_dir, "R1_init.fastq", "R2_init.fastq", 8, 0);
    let sortie_r1 = temp_dir.child("sortie_R1.fastq");
    let sortie_r2 = temp_dir.child("sortie_R2.fastq");

    cmd()
        .arg("-1").arg(r1_init.path())
        .arg("-2").arg(r2_init.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let (r1_full, r2_full) =
        generer_fastq_paire(&temp_dir, "R1_full.fastq", "R2_full.fastq", 15, 0);

    cmd()
        .arg("-1").arg(r1_full.path())
        .arg("-2").arg(r2_full.path())
        .arg("-o").arg(sortie_r1.path())
        .arg("-p").arg(sortie_r2.path())
        .assert()
        .success();

    let contenu_r1 = fs::read_to_string(sortie_r1.path()).unwrap();
    let contenu_r2 = fs::read_to_string(sortie_r2.path()).unwrap();

    // L'ID de base est la partie avant l'espace (commun à R1 et R2 pour chaque paire)
    let base_ids_r1: Vec<&str> = contenu_r1
        .lines()
        .filter(|l| l.starts_with('@'))
        .map(|l| l.trim_start_matches('@').split_whitespace().next().unwrap_or(l))
        .collect();

    let base_ids_r2: Vec<&str> = contenu_r2
        .lines()
        .filter(|l| l.starts_with('@'))
        .map(|l| l.trim_start_matches('@').split_whitespace().next().unwrap_or(l))
        .collect();

    assert_eq!(
        base_ids_r1.len(),
        base_ids_r2.len(),
        "R1 et R2 doivent avoir le même nombre de reads"
    );
    for (pos, (id_r1, id_r2)) in base_ids_r1.iter().zip(base_ids_r2.iter()).enumerate() {
        assert_eq!(
            id_r1, id_r2,
            "Désynchronisation à la position {} : R1={}, R2={}",
            pos, id_r1, id_r2
        );
    }
}