binseq 0.11.0

A high efficiency binary format for sequencing data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
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
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
//! Reader implementation for VBQ files.
//!
//! `MmapReader` memory-maps a VBQ file for zero-copy sequential or parallel
//! reading, handling compressed blocks, quality scores, paired-end reads, and
//! sequence headers. The embedded index at the end of the file drives random
//! access and parallel processing.

use std::fs::File;
use std::ops::Range;
use std::path::Path;
use std::sync::Arc;

use crate::utils::read_u64_le;
use bitnuc_deprec::BitSize;
use memmap2::Mmap;
use zstd::zstd_safe;

use super::{
    BlockHeader, BlockIndex, FileHeader,
    header::{SIZE_BLOCK_HEADER, SIZE_HEADER},
};
use crate::DEFAULT_QUALITY_SCORE;
use crate::vbq::index::{INDEX_END_MAGIC, INDEX_HEADER_SIZE, IndexHeader};
use crate::{
    BinseqRecord, ParallelProcessor, ParallelReader,
    error::{ReadError, Result},
};

/// Number of bases packed into each u64 word for the given bitsize
fn bases_per_word(bitsize: BitSize) -> usize {
    match bitsize {
        BitSize::Two => 32,
        BitSize::Four => 16,
    }
}

/// Number of u64 words needed to store `len` bases at the given bitsize
fn encoded_sequence_len(len: u64, bitsize: BitSize) -> usize {
    len.div_ceil(bases_per_word(bitsize) as u64) as usize
}

/// Represents a span (offset, length) into a buffer
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Span {
    offset: usize,
    len: usize,
}
impl Span {
    fn new(offset: usize, len: usize) -> Self {
        Self { offset, len }
    }

    /// Get a slice of bytes from a buffer
    fn slice<'a>(&self, buffer: &'a [u8]) -> &'a [u8] {
        &buffer[self.offset..self.offset + self.len]
    }

    /// Get a slice of u64s from a buffer
    fn slice_u64<'a>(&self, buffer: &'a [u64]) -> &'a [u64] {
        &buffer[self.offset..self.offset + self.len]
    }
}

/// Metadata for a single record, storing spans into rbuf
#[derive(Debug, Clone, Copy)]
struct RecordMetadata {
    flag: Option<u64>,
    slen: u64,
    xlen: u64,

    // Spans for primary sequence
    s_seq_span: Span,    // Encoded sequence words (u64s) (into `.sequences` buffer)
    s_qual_span: Span,   // Quality bytes
    s_header_span: Span, // Header bytes

    // Spans for extended sequence
    x_seq_span: Span,    // Encoded sequence words (u64s) (into `.sequences` buffer)
    x_qual_span: Span,   // Quality bytes
    x_header_span: Span, // Header bytes

    /// Indicates whether the record has quality scores
    has_quality: bool,
}

/// A reusable container for one block of VBQ records.
///
/// Cleared and refilled on each `MmapReader::read_block_into` call, so records
/// can be iterated without per-record allocation.
pub struct RecordBlock {
    /// Bitsize of the records in the block
    bitsize: BitSize,

    /// Global index of the first record in the block
    index: usize,

    /// Reusable buffer for temporary storage during decompression
    rbuf: Vec<u8>,

    /// Sequence data (u64s) - small copy during parsing
    sequences: Vec<u64>,

    /// Record metadata stored as compact spans
    records: Vec<RecordMetadata>,

    /// Maximum block size in bytes (from the file header)
    block_size: usize,

    /// Reusable zstd decompression context
    dctx: zstd_safe::DCtx<'static>,

    /// Reusable decoding buffer for the block
    dbuf: Vec<u8>,

    /// Reusable buffer for quality scores for the block
    qbuf: Vec<u8>,

    /// Default quality score for the block
    default_quality_score: u8,
}
impl RecordBlock {
    /// Creates a new empty `RecordBlock`.
    ///
    /// The block size must match the file header's; use `MmapReader::new_block()`
    /// to get this automatically.
    #[must_use]
    pub fn new(bitsize: BitSize, block_size: usize) -> Self {
        Self {
            bitsize,
            index: 0,
            block_size,
            records: Vec::default(),
            sequences: Vec::default(),
            rbuf: Vec::default(),
            dbuf: Vec::default(),
            dctx: zstd_safe::DCtx::create(),
            qbuf: Vec::default(),
            default_quality_score: DEFAULT_QUALITY_SCORE,
        }
    }

    /// Sets the default quality score for the block.
    pub fn set_default_quality_score(&mut self, score: u8) {
        self.default_quality_score = score;
        self.qbuf.clear();
    }

    /// Returns the number of records in this block.
    #[must_use]
    pub fn n_records(&self) -> usize {
        self.records.len()
    }

    /// Returns an iterator of zero-copy `RefRecord`s over the block.
    #[must_use]
    #[allow(clippy::iter_without_into_iter)]
    pub fn iter(&self) -> RecordBlockIter<'_> {
        RecordBlockIter::new(self)
    }

    /// Sets the global index of the first record in the block.
    fn update_index(&mut self, index: usize) {
        self.index = index;
    }

    /// Resets the block to an empty state for reuse.
    pub fn clear(&mut self) {
        self.index = 0;
        self.records.clear();
        self.sequences.clear();
        self.dbuf.clear();
        // Note: We keep rbuf allocated for reuse
        // Note: We keep qbuf allocated for reuse
    }

    /// Ingests uncompressed block bytes and parses the records.
    fn ingest_bytes(
        &mut self,
        bytes: &[u8],
        has_quality: bool,
        has_header: bool,
        has_flags: bool,
    ) -> Result<()> {
        if bytes.len() != self.block_size {
            return Err(ReadError::PartialRecord(bytes.len()).into());
        }
        self.rbuf.clear();
        self.rbuf.extend_from_slice(bytes);
        self.parse_records(has_quality, has_header, has_flags);
        Ok(())
    }

    /// Decompresses the given bytes and ingests them into the record block.
    fn ingest_compressed_bytes(
        &mut self,
        bytes: &[u8],
        has_quality: bool,
        has_header: bool,
        has_flags: bool,
    ) -> Result<()> {
        // Clear and ensure capacity
        self.rbuf.clear();
        if self.rbuf.capacity() < self.block_size {
            self.rbuf.reserve(self.block_size - self.rbuf.capacity());
        }

        // Reuse the decompression context - avoids allocation!
        let bytes_read = self
            .dctx
            .decompress(&mut self.rbuf, bytes)
            .map_err(|code| std::io::Error::other(zstd_safe::get_error_name(code)))?;

        if bytes_read != self.block_size {
            return Err(ReadError::PartialRecord(bytes_read).into());
        }

        self.parse_records(has_quality, has_header, has_flags);
        Ok(())
    }
    /// Parse records from rbuf, storing spans for all data
    fn parse_records(&mut self, has_quality: bool, has_header: bool, has_flags: bool) {
        self.records.clear();
        self.sequences.clear();

        let mut pos = 0;
        let bytes = &self.rbuf;

        loop {
            // Check if we have enough bytes for the minimum record header
            let min_header_size = if has_flags { 24 } else { 16 };
            if pos + min_header_size > bytes.len() {
                break;
            }

            // Read flag
            let flag = if has_flags {
                let flag = read_u64_le(&bytes[pos..pos + 8]);
                pos += 8;
                Some(flag)
            } else {
                None
            };

            // Read lengths
            let slen = read_u64_le(&bytes[pos..pos + 8]);
            pos += 8;
            let xlen = read_u64_le(&bytes[pos..pos + 8]);
            pos += 8;

            // Check for end of records
            if slen == 0 {
                break;
            }

            // Calculate sizes
            let s_seq_words = encoded_sequence_len(slen, self.bitsize);
            let x_seq_words = encoded_sequence_len(xlen, self.bitsize);

            // Primary sequence - store span into sequences Vec
            let s_seq_span = Span::new(self.sequences.len(), s_seq_words);
            for _ in 0..s_seq_words {
                let val = read_u64_le(&bytes[pos..pos + 8]);
                self.sequences.push(val);
                pos += 8;
            }

            // Primary quality - store span into rbuf
            let s_qual_span = if has_quality {
                let span = Span::new(pos, slen as usize);
                pos += slen as usize;
                span
            } else {
                Span::new(0, 0)
            };

            // Primary header - store span into rbuf
            let s_header_span = if has_header {
                let header_len = read_u64_le(&bytes[pos..pos + 8]) as usize;
                pos += 8;
                let span = Span::new(pos, header_len);
                pos += header_len;
                span
            } else {
                Span::new(0, 0)
            };

            // Extended sequence - store span into sequences Vec
            let x_seq_span = Span::new(self.sequences.len(), x_seq_words);
            for _ in 0..x_seq_words {
                let val = read_u64_le(&bytes[pos..pos + 8]);
                self.sequences.push(val);
                pos += 8;
            }

            // Extended quality - store span into rbuf
            let x_qual_span = if has_quality {
                let span = Span::new(pos, xlen as usize);
                pos += xlen as usize;
                span
            } else {
                Span::new(0, 0)
            };

            // Extended header - store span into rbuf
            let x_header_span = if has_header && xlen > 0 {
                let header_len = read_u64_le(&bytes[pos..pos + 8]) as usize;
                pos += 8;
                let span = Span::new(pos, header_len);
                pos += header_len;
                span
            } else {
                Span::new(0, 0)
            };

            // Update qbuf size
            if !has_quality {
                let max_size = slen.max(xlen) as usize;
                if self.qbuf.len() < max_size {
                    self.qbuf.resize(max_size, self.default_quality_score);
                }
            }

            // Store the record metadata - all spans!
            self.records.push(RecordMetadata {
                flag,
                slen,
                xlen,
                s_seq_span,
                s_qual_span,
                s_header_span,
                x_seq_span,
                x_qual_span,
                x_header_span,
                has_quality,
            });
        }
    }

    /// Decodes all sequences in the block at once.
    ///
    /// Each record's sequence is padded to the nearest u64, so the decoded
    /// buffer contains padding nucleotides; per-record spans track the real regions.
    pub fn decode_all(&mut self) -> Result<()> {
        if self.sequences.is_empty() {
            return Ok(());
        }
        self.dbuf.clear();
        match self.bitsize {
            BitSize::Two => {
                let num_bp = self.sequences.len() * 32;
                bitnuc_deprec::twobit::decode(&self.sequences, num_bp, &mut self.dbuf)
            }
            BitSize::Four => {
                let num_bp = self.sequences.len() * 16;
                bitnuc_deprec::fourbit::decode(&self.sequences, num_bp, &mut self.dbuf)
            }
        }?;
        Ok(())
    }

    /// Slice the decoded buffer for a record given a word span and base length
    fn decoded(&self, word_offset: usize, len: usize) -> Option<&[u8]> {
        if self.dbuf.is_empty() {
            return None;
        }
        // Calculate offset in decoded buffer (accounting for padding)
        let offset = word_offset * bases_per_word(self.bitsize);
        self.dbuf.get(offset..offset + len)
    }

    /// Get decoded primary sequence for a record by index
    #[must_use]
    pub fn get_decoded_s(&self, record_idx: usize) -> Option<&[u8]> {
        let meta = self.records.get(record_idx)?;
        self.decoded(meta.s_seq_span.offset, meta.slen as usize)
    }

    /// Get decoded extended sequence for a record by index
    #[must_use]
    pub fn get_decoded_x(&self, record_idx: usize) -> Option<&[u8]> {
        let meta = self.records.get(record_idx)?;
        if meta.xlen == 0 {
            return Some(&[]);
        }
        self.decoded(meta.x_seq_span.offset, meta.xlen as usize)
    }
}

pub struct RecordBlockIter<'a> {
    block: &'a RecordBlock,
    pos: usize,
    header_buffer: itoa::Buffer,
    qbuf: &'a [u8],
}
impl<'a> RecordBlockIter<'a> {
    #[must_use]
    pub fn new(block: &'a RecordBlock) -> Self {
        Self {
            block,
            pos: 0,
            header_buffer: itoa::Buffer::new(),
            qbuf: &block.qbuf,
        }
    }
}
impl<'a> Iterator for RecordBlockIter<'a> {
    type Item = RefRecord<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.block.records.len() {
            return None;
        }

        let meta = &self.block.records[self.pos];
        let index = (self.block.index + self.pos) as u64;
        let index_in_block = self.pos;

        let mut header_buf = [0; 20];
        let mut header_len = 0;
        if meta.s_header_span.len == 0 && meta.x_header_span.len == 0 {
            let header_str = self.header_buffer.format(index);
            header_len = header_str.len();
            header_buf[..header_len].copy_from_slice(header_str.as_bytes());
        }

        let (squal, xqual) = if meta.has_quality {
            // Record has quality scores, slice into rbuf using span
            (
                meta.s_qual_span.slice(&self.block.rbuf),
                meta.x_qual_span.slice(&self.block.rbuf),
            )
        } else {
            // Record does not have quality scores, use preallocated buffer for default scores
            (
                &self.qbuf[..meta.slen as usize],
                &self.qbuf[..meta.xlen as usize],
            )
        };

        // increment position
        {
            self.pos += 1;
        }

        Some(RefRecord {
            block: self.block,
            bitsize: self.block.bitsize,
            index,
            index_in_block,
            flag: meta.flag,
            slen: meta.slen,
            xlen: meta.xlen,
            // Slice into sequences Vec using span
            sbuf: meta.s_seq_span.slice_u64(&self.block.sequences),
            xbuf: meta.x_seq_span.slice_u64(&self.block.sequences),
            // Pass quality score buffers
            squal,
            xqual,
            // Slice into rbuf using span
            sheader: meta.s_header_span.slice(&self.block.rbuf),
            xheader: meta.x_header_span.slice(&self.block.rbuf),
            header_buf,
            header_len,
        })
    }
}

/// Zero-copy record reference
pub struct RefRecord<'a> {
    block: &'a RecordBlock,
    bitsize: BitSize,
    index: u64,
    index_in_block: usize,
    flag: Option<u64>,
    slen: u64,
    xlen: u64,
    sbuf: &'a [u64],
    xbuf: &'a [u64],
    squal: &'a [u8],
    xqual: &'a [u8],
    sheader: &'a [u8],
    xheader: &'a [u8],
    header_buf: [u8; 20],
    header_len: usize,
}

impl BinseqRecord for RefRecord<'_> {
    fn bitsize(&self) -> BitSize {
        self.bitsize
    }

    fn index(&self) -> u64 {
        self.index
    }

    fn sheader(&self) -> &[u8] {
        if self.sheader.is_empty() {
            &self.header_buf[..self.header_len]
        } else {
            self.sheader
        }
    }

    fn xheader(&self) -> &[u8] {
        if self.xheader.is_empty() {
            &self.header_buf[..self.header_len]
        } else {
            self.xheader
        }
    }

    fn flag(&self) -> Option<u64> {
        self.flag
    }

    fn slen(&self) -> u64 {
        self.slen
    }

    fn xlen(&self) -> u64 {
        self.xlen
    }

    fn sbuf(&self) -> &[u64] {
        self.sbuf
    }

    fn xbuf(&self) -> &[u64] {
        self.xbuf
    }

    fn squal(&self) -> &[u8] {
        self.squal
    }

    fn xqual(&self) -> &[u8] {
        self.xqual
    }

    /// Override this method since we can make use of block information
    fn decode_s(&self, buf: &mut Vec<u8>) -> Result<()> {
        if let Some(decoded) = self.block.get_decoded_s(self.index_in_block) {
            buf.extend_from_slice(decoded);
        } else {
            self.bitsize()
                .decode(self.sbuf(), self.slen() as usize, buf)?;
        }
        Ok(())
    }

    /// Override this method since we can make use of block information
    fn decode_x(&self, buf: &mut Vec<u8>) -> Result<()> {
        if let Some(decoded) = self.block.get_decoded_x(self.index_in_block) {
            buf.extend_from_slice(decoded);
        } else {
            self.bitsize()
                .decode(self.xbuf(), self.xlen() as usize, buf)?;
        }
        Ok(())
    }

    /// Override this method since we can make use of block information
    fn sseq(&self) -> &[u8] {
        self.block
            .get_decoded_s(self.index_in_block)
            .expect("Reader was built without batch-decoding")
    }

    /// Override this method since we can make use of block information
    fn xseq(&self) -> &[u8] {
        self.block
            .get_decoded_x(self.index_in_block)
            .expect("Reader was built without batch-decoding")
    }
}

/// Memory-mapped reader for VBQ files.
///
/// Reads [`RecordBlock`]s sequentially via [`MmapReader::read_block_into`], or
/// processes records in parallel via the [`ParallelReader`] trait. Blocks yield
/// [`RefRecord`]s implementing the [`BinseqRecord`] trait.
///
/// # Examples
///
/// ```
/// use binseq::vbq::MmapReader;
/// use binseq::{BinseqRecord, Result};
///
/// fn main() -> Result<()> {
///     let mut reader = MmapReader::new("./data/subset.vbq")?;
///     let mut seq_buffer = Vec::new();
///     let mut block = reader.new_block();
///
///     while reader.read_block_into(&mut block)? {
///         for record in block.iter() {
///             record.decode_s(&mut seq_buffer)?;
///             println!("Header: {}", std::str::from_utf8(record.sheader()).unwrap_or(""));
///             println!("Sequence: {}", std::str::from_utf8(&seq_buffer).unwrap_or(""));
///             seq_buffer.clear();
///         }
///     }
///     Ok(())
/// }
/// ```
pub struct MmapReader {
    /// Memory-mapped file contents for efficient access
    mmap: Arc<Mmap>,

    /// Parsed header information from the file
    header: FileHeader,

    /// Current cursor position in the file (in bytes)
    pos: usize,

    /// Total number of records read from the file so far
    total: usize,

    /// Whether to decode sequences at once in each block
    decode_block: bool,

    /// Default quality score for this reader
    default_quality_score: u8,
}
impl MmapReader {
    /// Opens and memory-maps a VBQ file, positioned at the first record block.
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
        // Verify it's a regular file before attempting to map
        let file = File::open(&path)?;
        if !file.metadata()?.is_file() {
            return Err(ReadError::InvalidFileType.into());
        }

        // Safety: The file is open and won't be modified while mapped
        let mmap = unsafe { Mmap::map(&file)? };

        // Read header from mapped memory
        let header = {
            let mut header_bytes = [0u8; SIZE_HEADER];
            header_bytes.copy_from_slice(&mmap[..SIZE_HEADER]);
            FileHeader::from_bytes(&header_bytes)?
        };

        Ok(Self {
            mmap: Arc::new(mmap),
            header,
            pos: SIZE_HEADER,
            total: 0,
            decode_block: true,
            default_quality_score: DEFAULT_QUALITY_SCORE,
        })
    }

    pub fn set_default_quality_score(&mut self, score: u8) {
        self.default_quality_score = score;
    }

    /// Creates a new empty `RecordBlock` sized to this file's block size.
    #[must_use]
    pub fn new_block(&self) -> RecordBlock {
        let mut block = RecordBlock::new(self.header.bits, self.header.block as usize);
        block.set_default_quality_score(self.default_quality_score);
        block
    }

    /// Sets whether each block's sequences are batch-decoded during parallel processing.
    pub fn set_decode_block(&mut self, decode_block: bool) {
        self.decode_block = decode_block;
    }

    /// Returns a copy of the file's header.
    #[must_use]
    pub fn header(&self) -> FileHeader {
        self.header
    }

    /// Checks if the file contains paired records
    #[must_use]
    pub fn is_paired(&self) -> bool {
        self.header.is_paired()
    }

    /// Reads the next block of records into `block`, decompressing if needed.
    ///
    /// Returns `Ok(false)` when the end of the data blocks is reached.
    pub fn read_block_into(&mut self, block: &mut RecordBlock) -> Result<bool> {
        // Clear the block
        block.clear();

        // Validate the next block header is within bounds and present
        if self.pos + SIZE_BLOCK_HEADER > self.mmap.len() {
            return Ok(false);
        }
        let mut header_bytes = [0u8; SIZE_BLOCK_HEADER];
        header_bytes.copy_from_slice(&self.mmap[self.pos..self.pos + SIZE_BLOCK_HEADER]);
        let header = match BlockHeader::from_bytes(&header_bytes) {
            Ok(header) => {
                self.pos += SIZE_BLOCK_HEADER;
                header
            }
            // Bytes left - but not a BlockHeader - could be the index
            Err(e) => {
                let mut index_header_bytes = [0u8; INDEX_HEADER_SIZE];
                index_header_bytes
                    .copy_from_slice(&self.mmap[self.pos..self.pos + INDEX_HEADER_SIZE]);
                if IndexHeader::from_bytes(&index_header_bytes).is_ok() {
                    // Expected end of file
                    return Ok(false);
                }
                return Err(e);
            }
        };

        // Read the block contents
        let rbound = if self.header.compressed {
            header.size as usize
        } else {
            self.header.block as usize
        };
        if self.pos + rbound > self.mmap.len() {
            return Err(ReadError::UnexpectedEndOfFile(self.pos).into());
        }
        let block_buffer = &self.mmap[self.pos..self.pos + rbound];
        if self.header.compressed {
            block.ingest_compressed_bytes(
                block_buffer,
                self.header.qual,
                self.header.headers,
                self.header.flags,
            )?;
        } else {
            block.ingest_bytes(
                block_buffer,
                self.header.qual,
                self.header.headers,
                self.header.flags,
            )?;
        }

        // Update the block index
        block.update_index(self.total);

        self.pos += rbound;
        self.total += header.records as usize;

        Ok(true)
    }

    /// Loads the embedded block index from the end of the file.
    pub fn load_index(&self) -> Result<BlockIndex> {
        let start_pos_magic = self.mmap.len() - 8;
        let start_pos_index_size = start_pos_magic - 8;

        // Validate the magic number
        let magic = read_u64_le(&self.mmap[start_pos_magic..]);
        if magic != INDEX_END_MAGIC {
            return Err(ReadError::MissingIndexEndMagic.into());
        }

        // Get the index size
        let index_size = read_u64_le(&self.mmap[start_pos_index_size..start_pos_magic]);

        // Determine the start position of the index bytes
        let start_pos_index = start_pos_index_size - index_size as usize;

        // Slice into the index bytes
        let index_bytes = &self.mmap[start_pos_index..start_pos_index_size];

        // Build the index from the bytes
        BlockIndex::from_bytes(index_bytes)
    }

    pub fn num_records(&self) -> Result<usize> {
        let index = self.load_index()?;
        Ok(index.num_records())
    }
}

impl ParallelReader for MmapReader {
    /// Processes all records in parallel by distributing blocks across threads.
    ///
    /// The processor is cloned per thread and may borrow from the caller's scope.
    fn process_parallel<P: ParallelProcessor>(
        self,
        processor: P,
        num_threads: usize,
    ) -> Result<()> {
        let num_records = self.num_records()?;
        self.process_parallel_range(processor, num_threads, 0..num_records)
    }

    /// Processes only the records within `range` in parallel.
    fn process_parallel_range<P: ParallelProcessor>(
        self,
        processor: P,
        num_threads: usize,
        range: Range<usize>,
    ) -> Result<()> {
        // Calculate the number of threads to use
        let num_threads = crate::parallel::clamp_threads(num_threads);

        // Generate or load the index first
        let index = self.load_index()?;

        // Validate range
        let total_records = index.num_records();
        crate::parallel::validate_range(total_records, &range)?;

        // Find blocks that contain records in the specified range
        let relevant_blocks = index
            .ranges()
            .iter()
            .filter(|r| {
                let iv_start = r.cumulative_records as usize;
                let iv_end = (r.cumulative_records + u64::from(r.block_records)) as usize;
                iv_start < range.end && iv_end > range.start
            })
            .copied()
            .collect::<Vec<_>>();

        if relevant_blocks.is_empty() {
            return Ok(()); // No relevant blocks
        }

        // Calculate block assignments for threads
        let blocks_per_thread = relevant_blocks.len().div_ceil(num_threads);

        // Create shared resources
        let mmap: &[u8] = &self.mmap;
        let header = self.header;

        std::thread::scope(|s| -> Result<()> {
            // Spawn worker threads
            let mut handles = Vec::new();

            for thread_id in 0..num_threads {
                // Calculate this thread's block range
                let start_block_idx = thread_id * blocks_per_thread;
                let end_block_idx =
                    std::cmp::min((thread_id + 1) * blocks_per_thread, relevant_blocks.len());

                if start_block_idx >= relevant_blocks.len() {
                    continue;
                }

                let mut proc = processor.clone();
                proc.set_tid(thread_id);

                // Get block ranges for this thread
                let thread_blocks = &relevant_blocks[start_block_idx..end_block_idx];

                let handle = s.spawn(move || -> Result<()> {
                    // Create block to reuse for processing (within thread)
                    let mut record_block = RecordBlock::new(header.bits, header.block as usize);

                    // Process each assigned block
                    for &block_range in thread_blocks {
                        // Clear the block for reuse
                        record_block.clear();

                        // Skip the block header to get to data
                        let block_start = block_range.start_offset as usize + SIZE_BLOCK_HEADER;
                        let block_data = &mmap[block_start..block_start + block_range.len as usize];

                        // Ingest data according to the compression setting
                        if header.compressed {
                            record_block.ingest_compressed_bytes(
                                block_data,
                                header.qual,
                                header.headers,
                                header.flags,
                            )?;
                        } else {
                            record_block.ingest_bytes(
                                block_data,
                                header.qual,
                                header.headers,
                                header.flags,
                            )?;
                        }

                        // Update the record block index
                        record_block.update_index(block_range.cumulative_records as usize);

                        // decode the data
                        if self.decode_block {
                            record_block.decode_all()?;
                        }

                        // Process records in this block that fall within our range
                        for record in record_block.iter() {
                            let global_record_idx = record.index as usize;

                            // Only process records within our specified range
                            if global_record_idx >= range.start && global_record_idx < range.end {
                                proc.process_record(record)?;
                            }
                        }

                        // Signal batch completion
                        proc.on_batch_complete()?;
                    }

                    // Signal thread completion
                    proc.on_thread_complete()?;

                    Ok(())
                });

                handles.push(handle);
            }

            // Wait for all threads to complete
            handles.into_iter().try_for_each(|h| h.join().unwrap())
        })
    }
}

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

    const TEST_VBQ_FILE: &str = "./data/subset.vbq";

    // ==================== MmapReader Basic Tests ====================

    #[test]
    fn test_mmap_reader_new() {
        let reader = MmapReader::new(TEST_VBQ_FILE);
        assert!(reader.is_ok(), "Failed to create VBQ reader");
    }

    #[test]
    fn test_mmap_reader_num_records() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let num_records = reader.num_records();
        assert!(num_records.is_ok(), "Failed to get num_records");
        assert!(num_records.unwrap() > 0, "Expected non-zero records");
    }

    #[test]
    fn test_mmap_reader_is_paired() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        // The fixture file contains paired records
        assert!(reader.is_paired());
    }

    #[test]
    fn test_mmap_reader_header_access() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let header = &reader.header;
        assert!(header.block > 0, "Expected non-zero block size");
        assert_eq!(header.magic, 0x5145_5356, "Expected VSEQ magic number");
    }

    // ==================== RecordBlock Tests ====================

    #[test]
    fn test_new_block() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let block = reader.new_block();

        assert_eq!(block.bitsize, reader.header.bits);
        assert!(block.n_records() == 0, "New block should be empty");
    }

    #[test]
    fn test_record_block_creation() {
        let block = RecordBlock::new(BitSize::Two, 1024);

        assert_eq!(block.bitsize, BitSize::Two);
        assert_eq!(block.n_records(), 0);
    }

    #[test]
    fn test_record_block_clear() {
        let mut block = RecordBlock::new(BitSize::Two, 1024);

        // Block starts empty
        assert_eq!(block.n_records(), 0);

        // Clear should not panic on empty block
        block.clear();
        assert_eq!(block.n_records(), 0);
    }

    #[test]
    fn test_record_block_set_default_quality() {
        let mut block = RecordBlock::new(BitSize::Two, 1024);
        let custom_score = 42u8;

        block.set_default_quality_score(custom_score);
        assert_eq!(block.default_quality_score, custom_score);
    }

    // ==================== Block Reading Tests ====================

    #[test]
    fn test_read_block_into() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        let result = reader.read_block_into(&mut block);
        assert!(result.is_ok(), "Failed to read block");

        if result.unwrap() {
            assert!(block.n_records() > 0, "Block should contain records");
        }
    }

    #[test]
    fn test_read_multiple_blocks() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        let mut blocks_read = 0;
        let max_blocks = 5;

        while reader.read_block_into(&mut block).unwrap() && blocks_read < max_blocks {
            assert!(block.n_records() > 0, "Each block should have records");
            blocks_read += 1;
        }

        assert!(blocks_read > 0, "Should read at least one block");
    }

    #[test]
    fn test_block_iteration() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            let num_records = block.n_records();
            let mut count = 0;

            for record in block.iter() {
                assert!(record.slen() > 0, "Record should have non-zero length");
                count += 1;
            }

            assert_eq!(count, num_records, "Iterator should yield all records");
        }
    }

    // ==================== Record Access Tests ====================

    #[test]
    fn test_record_sequence_data() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            // Decode all sequences in the block
            block.decode_all().unwrap();

            if let Some(record) = block.iter().next() {
                let sseq = record.sseq();
                assert!(!sseq.is_empty(), "Sequence should not be empty");

                let slen = record.slen();
                assert_eq!(sseq.len(), slen as usize, "Sequence length mismatch");
            }
        }
    }

    #[test]
    fn test_record_header_data() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            for record in block.iter() {
                let sheader = record.sheader();
                // Header may be empty if not included in file
                if !sheader.is_empty() {
                    // Should be valid UTF-8 if present
                    let _ = std::str::from_utf8(sheader);
                }
            }
        }
    }

    #[test]
    fn test_record_quality_data() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            for record in block.iter() {
                let squal = record.squal();
                let slen = record.slen() as usize;

                if !squal.is_empty() {
                    assert_eq!(
                        squal.len(),
                        slen,
                        "Quality length should match sequence length"
                    );
                }
            }
        }
    }

    #[test]
    fn test_record_bitsize() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            for record in block.iter() {
                let bitsize = record.bitsize();
                assert!(
                    matches!(bitsize, BitSize::Two | BitSize::Four),
                    "Bitsize should be Two or Four"
                );
            }
        }
    }

    // ==================== Default Quality Score Tests ====================

    #[test]
    fn test_set_default_quality_score() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let custom_score = 42u8;

        reader.set_default_quality_score(custom_score);
        assert_eq!(reader.default_quality_score, custom_score);

        let block = reader.new_block();
        assert_eq!(block.default_quality_score, custom_score);
    }

    // ==================== Decode Block Feature Tests ====================

    #[test]
    fn test_set_decode_block() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();

        reader.set_decode_block(true);
        // Just verify it doesn't panic - actual behavior depends on reading

        reader.set_decode_block(false);
        // Verify we can toggle it
    }

    #[test]
    fn test_decode_block_affects_reading() {
        let mut reader1 = MmapReader::new(TEST_VBQ_FILE).unwrap();
        reader1.set_decode_block(true);
        let mut block1 = reader1.new_block();

        let mut reader2 = MmapReader::new(TEST_VBQ_FILE).unwrap();
        reader2.set_decode_block(false);
        let mut block2 = reader2.new_block();

        // Both should read successfully
        let result1 = reader1.read_block_into(&mut block1);
        let result2 = reader2.read_block_into(&mut block2);

        assert!(result1.is_ok() && result2.is_ok());
    }

    // ==================== Parallel Processing Tests ====================

    #[derive(Clone, Default)]
    struct VbqCountingProcessor {
        count: Arc<std::sync::Mutex<usize>>,
    }

    impl ParallelProcessor for VbqCountingProcessor {
        fn process_record<R: BinseqRecord>(&mut self, _record: R) -> Result<()> {
            *self.count.lock().unwrap() += 1;
            Ok(())
        }
    }

    #[test]
    fn test_parallel_processing() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let num_records_result = reader.num_records();

        // Skip test if we can't determine record count
        if num_records_result.is_err() {
            return;
        }

        let num_records = num_records_result.unwrap();

        let processor = VbqCountingProcessor::default();

        let result = reader.process_parallel(processor.clone(), 2);

        // Parallel processing might not be supported for all VBQ files
        if result.is_ok() {
            let final_count = *processor.count.lock().unwrap();
            assert_eq!(final_count, num_records,);
        }
    }

    #[test]
    fn test_parallel_processing_range() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let num_records_result = reader.num_records();

        // Skip test if we can't determine record count
        if num_records_result.is_err() {
            return;
        }

        let num_records = num_records_result.unwrap();

        if num_records >= 100 {
            let start = 10;
            let end = 50;
            let expected_count = end - start;

            let processor = VbqCountingProcessor::default();

            let result = reader.process_parallel_range(processor.clone(), 2, start..end);

            // Parallel processing might not be supported for all VBQ files
            if result.is_ok() {
                let final_count = *processor.count.lock().unwrap();
                // The count should be reasonable
                assert_eq!(
                    final_count, expected_count,
                    "Processed count should match expected range"
                );
            }
        }
    }

    // ==================== Span Tests ====================

    #[test]
    fn test_span_creation() {
        let span = Span::new(10, 20);
        assert_eq!(span.offset, 10);
        assert_eq!(span.len, 20);
    }

    #[test]
    fn test_span_default() {
        let span = Span::default();
        assert_eq!(span.offset, 0);
        assert_eq!(span.len, 0);
    }

    // ==================== Error Handling Tests ====================

    #[test]
    fn test_nonexistent_file() {
        let result = MmapReader::new("./data/nonexistent.vbq");
        assert!(result.is_err(), "Should fail on nonexistent file");
    }

    #[test]
    fn test_invalid_file_format() {
        // Try to open a non-VBQ file as VBQ
        let result = MmapReader::new("./Cargo.toml");
        // This should fail during header validation
        assert!(result.is_err(), "Should fail on invalid file format");
    }

    // ==================== Index Loading Tests ====================

    #[test]
    fn test_load_index() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let index_result = reader.load_index();

        assert!(index_result.is_ok(), "Should be able to load index");

        let index = index_result.unwrap();
        assert!(index.num_records() > 0, "Index should have records");
    }

    #[test]
    fn test_index_consistency() {
        let reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let num_records_from_reader = reader.num_records().unwrap();

        let index = reader.load_index().unwrap();
        let num_records_from_index = index.num_records();

        assert_eq!(
            num_records_from_reader, num_records_from_index,
            "Reader and index should report same number of records"
        );
    }

    // ==================== RecordBlock Decoded Access Tests ====================

    #[test]
    fn test_get_decoded_s() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        reader.set_decode_block(true);
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() && block.n_records() > 0 {
            let decoded = block.get_decoded_s(0);
            if let Some(seq) = decoded {
                assert!(!seq.is_empty(), "Decoded sequence should not be empty");
            }
        }
    }

    #[test]
    fn test_get_decoded_x() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        reader.set_decode_block(true);
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() && block.n_records() > 0 {
            // Extended sequence may be empty for non-paired reads
            let decoded = block.get_decoded_x(0);
            // Just verify it doesn't panic
            let _ = decoded;
        }
    }

    #[test]
    fn test_get_decoded_out_of_bounds() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() {
            let num_records = block.n_records();

            // Try to access beyond bounds
            let decoded = block.get_decoded_s(num_records + 100);
            assert!(decoded.is_none(), "Should return None for out of bounds");
        }
    }

    // ==================== Helper Function Tests ====================

    #[test]
    fn test_encoded_sequence_len_two_bit() {
        // 2-bit encoding: 32 nucleotides per u64
        assert_eq!(encoded_sequence_len(32, BitSize::Two), 1);
        assert_eq!(encoded_sequence_len(64, BitSize::Two), 2);
        assert_eq!(encoded_sequence_len(33, BitSize::Two), 2); // Rounds up
        assert_eq!(encoded_sequence_len(1, BitSize::Two), 1);
    }

    #[test]
    fn test_encoded_sequence_len_four_bit() {
        // 4-bit encoding: 16 nucleotides per u64
        assert_eq!(encoded_sequence_len(16, BitSize::Four), 1);
        assert_eq!(encoded_sequence_len(32, BitSize::Four), 2);
        assert_eq!(encoded_sequence_len(17, BitSize::Four), 2); // Rounds up
        assert_eq!(encoded_sequence_len(1, BitSize::Four), 1);
    }

    // ==================== Record Iterator Tests ====================

    #[test]
    fn test_record_block_iter_creation() {
        let block = RecordBlock::new(BitSize::Two, 1024);
        let iter = RecordBlockIter::new(&block);

        // Iterator on empty block should yield nothing
        assert_eq!(iter.count(), 0);
    }

    #[test]
    fn test_record_iteration_multiple_times() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        if reader.read_block_into(&mut block).unwrap() && block.n_records() > 0 {
            let num_records = block.n_records();

            // First iteration
            let count1 = block.iter().count();
            assert_eq!(count1, num_records);

            // Second iteration should yield same count
            let count2 = block.iter().count();
            assert_eq!(count2, num_records);
        }
    }

    // ==================== Paired Read Tests ====================

    #[test]
    fn test_paired_record_data() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();

        if reader.is_paired() {
            let mut block = reader.new_block();

            if reader.read_block_into(&mut block).unwrap() {
                // Decode all sequences in the block
                block.decode_all().unwrap();

                for record in block.iter() {
                    let xlen = record.xlen();

                    if xlen > 0 {
                        let xseq = record.xseq();
                        assert_eq!(
                            xseq.len(),
                            xlen as usize,
                            "Extended sequence length should match xlen"
                        );
                    }
                }
            }
        }
    }

    // ==================== Edge Cases ====================

    #[test]
    fn test_empty_block_iteration() {
        let block = RecordBlock::new(BitSize::Two, 1024);

        let mut count = 0;
        for _ in block.iter() {
            count += 1;
        }

        assert_eq!(count, 0, "Empty block should yield no records");
    }

    #[test]
    fn test_reader_reset_by_new_block() {
        let mut reader = MmapReader::new(TEST_VBQ_FILE).unwrap();
        let mut block = reader.new_block();

        // Read first block
        if reader.read_block_into(&mut block).unwrap() {
            let first_count = block.n_records();

            // Read second block (overwrites first)
            if reader.read_block_into(&mut block).unwrap() {
                let second_count = block.n_records();

                // Counts may differ, but both should be > 0
                assert!(first_count > 0 && second_count > 0);
            }
        }
    }
}