Skip to main content

gtars_refget/digest/
types.rs

1//! Core types for sequence collections - WASM-safe.
2//!
3//! This module contains the fundamental data structures for representing sequences
4//! and sequence collections. All types here are WASM-compatible and don't require
5//! filesystem access.
6
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::fmt::Display;
10use std::path::PathBuf;
11use std::sync::Arc;
12
13use super::algorithms::{canonicalize_json, md5, sha512t24u};
14use super::alphabet::{AlphabetType, guess_alphabet};
15
16/// Metadata for a single sequence, including its name, length, digests, and alphabet type.
17#[derive(Clone, Debug, Serialize, Deserialize)]
18pub struct SequenceMetadata {
19    pub name: String,
20    /// Description from FASTA header (text after first whitespace).
21    #[serde(default)]
22    pub description: Option<String>,
23    pub length: usize,
24    pub sha512t24u: String,
25    pub md5: String,
26    pub alphabet: AlphabetType,
27    pub fai: Option<FaiMetadata>,
28}
29
30impl Default for SequenceMetadata {
31    fn default() -> Self {
32        Self {
33            name: String::new(),
34            description: None,
35            length: 0,
36            sha512t24u: String::new(),
37            md5: String::new(),
38            alphabet: AlphabetType::Ascii,
39            fai: None,
40        }
41    }
42}
43
44/// FASTA index (FAI) metadata for a sequence.
45/// This data is only present when a sequence was loaded from a FASTA file.
46#[derive(Clone, Debug, Serialize, Deserialize)]
47pub struct FaiMetadata {
48    pub offset: u64,     // byte offset to first base of sequence data
49    pub line_bases: u32, // number of bases per line
50    pub line_bytes: u32, // number of bytes per line (including newline chars)
51}
52
53/// A representation of a single sequence that includes metadata and optionally data.
54/// Combines sequence metadata with optional raw/encoded data.
55///
56/// This enum has two variants:
57/// - `Stub`: Contains only metadata, no sequence data loaded
58/// - `Full`: Contains both metadata and the actual sequence data
59#[derive(Clone, Debug)]
60pub enum SequenceRecord {
61    /// A sequence record with only metadata, no sequence data
62    Stub(SequenceMetadata),
63    /// A sequence record with both metadata and sequence data.
64    ///
65    /// The sequence bytes are held in an `Arc` so that streaming readers
66    /// (see `ReadonlyRefgetStore::stream_sequence`) can share ownership
67    /// without cloning the underlying buffer. This preserves the O(1)
68    /// memory claim of `stream_sequence` for in-memory records.
69    Full {
70        metadata: SequenceMetadata,
71        sequence: Arc<Vec<u8>>,
72    },
73}
74
75impl SequenceRecord {
76    /// Get metadata regardless of variant
77    pub fn metadata(&self) -> &SequenceMetadata {
78        match self {
79            SequenceRecord::Stub(meta) => meta,
80            SequenceRecord::Full { metadata, .. } => metadata,
81        }
82    }
83
84    /// Get sequence data if present
85    pub fn sequence(&self) -> Option<&[u8]> {
86        match self {
87            SequenceRecord::Stub(_) => None,
88            SequenceRecord::Full { sequence, .. } => Some(&sequence[..]),
89        }
90    }
91
92    /// Get the sequence data as a shared Arc, if present.
93    ///
94    /// This lets callers share ownership of the underlying buffer without
95    /// copying. Used by `stream_sequence` to stream bytes from an in-memory
96    /// `Full` record without allocating a second copy.
97    pub fn sequence_arc(&self) -> Option<Arc<Vec<u8>>> {
98        match self {
99            SequenceRecord::Stub(_) => None,
100            SequenceRecord::Full { sequence, .. } => Some(Arc::clone(sequence)),
101        }
102    }
103
104    /// Check if sequence data is loaded (Full) or just metadata (Stub).
105    pub fn is_loaded(&self) -> bool {
106        match self {
107            SequenceRecord::Stub(_) => false,
108            SequenceRecord::Full { .. } => true,
109        }
110    }
111
112    /// Load data into a Stub/Full record, converting to Full (takes ownership).
113    pub fn with_data(self, sequence: Vec<u8>) -> Self {
114        let metadata = match self {
115            SequenceRecord::Stub(m) => m,
116            SequenceRecord::Full { metadata, .. } => metadata,
117        };
118        SequenceRecord::Full {
119            metadata,
120            sequence: Arc::new(sequence),
121        }
122    }
123
124    /// Load data into a Stub record in-place, converting it to Full.
125    /// If already Full, replaces the existing sequence data.
126    pub fn load_data(&mut self, sequence: Vec<u8>) {
127        match self {
128            SequenceRecord::Stub(metadata) => {
129                let metadata = std::mem::take(metadata);
130                *self = SequenceRecord::Full {
131                    metadata,
132                    sequence: Arc::new(sequence),
133                };
134            }
135            SequenceRecord::Full {
136                sequence: existing, ..
137            } => {
138                // Just replace the sequence data
139                *existing = Arc::new(sequence);
140            }
141        }
142    }
143
144    /// Decodes the sequence data to a string.
145    ///
146    /// This method attempts to decode the sequence data stored in this record.
147    /// It handles both raw (uncompressed UTF-8) and encoded (bit-packed) data.
148    /// The decoding strategy depends on the alphabet type:
149    /// - For ASCII alphabet: data is already in raw form, just convert to string
150    /// - For other alphabets: attempt encoded decoding first, fall back to raw
151    ///
152    /// # Returns
153    ///
154    /// * `Some(String)` - The decoded sequence if data is loaded
155    /// * `None` - If no data is loaded in this record
156    pub fn decode(&self) -> Option<String> {
157        use super::alphabet::lookup_alphabet;
158        use super::encoder::decode_substring_from_bytes;
159
160        let (metadata, data): (&SequenceMetadata, &[u8]) = match self {
161            SequenceRecord::Stub(_) => return None,
162            SequenceRecord::Full { metadata, sequence } => (metadata, sequence.as_slice()),
163        };
164
165        // For ASCII alphabet (8 bits per symbol), the data is always stored raw
166        if metadata.alphabet == AlphabetType::Ascii {
167            return String::from_utf8(data.to_vec()).ok();
168        }
169
170        let alphabet = lookup_alphabet(&metadata.alphabet);
171        let bps = alphabet.bits_per_symbol;
172        let expected_encoded = metadata.length.saturating_mul(bps).div_ceil(8);
173        if data.len() == metadata.length && data.len() != expected_encoded {
174            if let Ok(raw_string) = String::from_utf8(data.to_vec()) { return Some(raw_string); }
175        }
176        let decoded_bytes = decode_substring_from_bytes(&data[..], 0, metadata.length, alphabet);
177        String::from_utf8(decoded_bytes).ok()
178    }
179}
180
181impl Display for SequenceRecord {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        write!(
184            f,
185            "SequenceRecord: {} (length: {}, alphabet: {}, ga4gh: {:02x?}, md5: {:02x?})",
186            &self.metadata().name,
187            &self.metadata().length,
188            &self.metadata().alphabet,
189            &self.metadata().sha512t24u,
190            &self.metadata().md5
191        )?;
192        Ok(())
193    }
194}
195
196/// A struct representing the first level of digests for a refget sequence collection.
197#[derive(Debug, Serialize, Deserialize, Clone)]
198pub struct SeqColDigestLvl1 {
199    pub sequences_digest: String,
200    pub names_digest: String,
201    pub lengths_digest: String,
202}
203
204impl SeqColDigestLvl1 {
205    /// Compute collection digest from lvl1 digests
206    pub fn to_digest(&self) -> String {
207        // Create JSON object with the lvl1 digest strings
208        let mut lvl1_object = serde_json::Map::new();
209        lvl1_object.insert(
210            "names".to_string(),
211            serde_json::Value::String(self.names_digest.clone()),
212        );
213        lvl1_object.insert(
214            "sequences".to_string(),
215            serde_json::Value::String(self.sequences_digest.clone()),
216        );
217
218        let lvl1_json = serde_json::Value::Object(lvl1_object);
219
220        // Canonicalize the JSON object and compute collection digest
221        let lvl1_canonical = canonicalize_json(&lvl1_json);
222        sha512t24u(lvl1_canonical.as_bytes())
223    }
224
225    /// Compute lvl1 digests from a collection of SequenceMetadata
226    pub fn from_metadata(metadata_vec: &[&SequenceMetadata]) -> Self {
227        use serde_json::Value;
228
229        // Extract arrays for each field
230        let sequences: Vec<String> = metadata_vec
231            .iter()
232            .map(|md| format!("SQ.{}", md.sha512t24u))
233            .collect();
234        let names: Vec<&str> = metadata_vec.iter().map(|md| md.name.as_str()).collect();
235        let lengths: Vec<usize> = metadata_vec.iter().map(|md| md.length).collect();
236
237        // Convert to JSON Values and canonicalize
238        let sequences_json = Value::Array(
239            sequences
240                .iter()
241                .map(|s| Value::String(s.to_string()))
242                .collect(),
243        );
244        let names_json = Value::Array(names.iter().map(|s| Value::String(s.to_string())).collect());
245        let lengths_json = Value::Array(
246            lengths
247                .iter()
248                .map(|l| Value::Number(serde_json::Number::from(*l)))
249                .collect(),
250        );
251
252        // Canonicalize to JCS format
253        let sequences_canonical = canonicalize_json(&sequences_json);
254        let names_canonical = canonicalize_json(&names_json);
255        let lengths_canonical = canonicalize_json(&lengths_json);
256
257        // Hash the canonicalized arrays
258        SeqColDigestLvl1 {
259            sequences_digest: sha512t24u(sequences_canonical.as_bytes()),
260            names_digest: sha512t24u(names_canonical.as_bytes()),
261            lengths_digest: sha512t24u(lengths_canonical.as_bytes()),
262        }
263    }
264
265    /// Compute name_length_pairs digest.
266    ///
267    /// Algorithm: for each sequence, create {"length": L, "name": "N"},
268    /// canonicalize each to JSON, digest each, collect into array,
269    /// canonicalize array, digest array.
270    pub fn compute_name_length_pairs_digest(metadata: &[&SequenceMetadata]) -> String {
271        use serde_json::Value;
272
273        // Build array of {"length": N, "name": "X"} pair objects
274        let pairs: Vec<Value> = metadata
275            .iter()
276            .map(|md| {
277                let mut obj = serde_json::Map::new();
278                obj.insert(
279                    "length".to_string(),
280                    Value::Number(serde_json::Number::from(md.length)),
281                );
282                obj.insert("name".to_string(), Value::String(md.name.clone()));
283                Value::Object(obj)
284            })
285            .collect();
286
287        // Canonicalize the entire array of pair objects, then digest
288        let canonical = canonicalize_json(&Value::Array(pairs));
289        sha512t24u(canonical.as_bytes())
290    }
291
292    /// Compute sorted_name_length_pairs digest (order-invariant coordinate system).
293    ///
294    /// Algorithm: same as name_length_pairs but sort the individual pair digests
295    /// lexicographically before digesting the array.
296    pub fn compute_sorted_name_length_pairs_digest(metadata: &[&SequenceMetadata]) -> String {
297        use serde_json::Value;
298
299        let mut pair_digests: Vec<String> = metadata
300            .iter()
301            .map(|md| {
302                let mut obj = serde_json::Map::new();
303                obj.insert(
304                    "length".to_string(),
305                    Value::Number(serde_json::Number::from(md.length)),
306                );
307                obj.insert("name".to_string(), Value::String(md.name.clone()));
308                let canonical = canonicalize_json(&Value::Object(obj));
309                sha512t24u(canonical.as_bytes())
310            })
311            .collect();
312
313        pair_digests.sort();
314
315        let array_json = Value::Array(
316            pair_digests
317                .iter()
318                .map(|d| Value::String(d.clone()))
319                .collect(),
320        );
321        let canonical = canonicalize_json(&array_json);
322        sha512t24u(canonical.as_bytes())
323    }
324
325    /// Compute sorted_sequences digest.
326    ///
327    /// Algorithm: take sequences array (with SQ. prefix), sort lexicographically,
328    /// canonicalize, digest.
329    pub fn compute_sorted_sequences_digest(metadata: &[&SequenceMetadata]) -> String {
330        use serde_json::Value;
331
332        let mut sequences: Vec<String> = metadata
333            .iter()
334            .map(|md| format!("SQ.{}", md.sha512t24u))
335            .collect();
336
337        sequences.sort();
338
339        let array_json = Value::Array(
340            sequences
341                .iter()
342                .map(|s| Value::String(s.clone()))
343                .collect(),
344        );
345        let canonical = canonicalize_json(&array_json);
346        sha512t24u(canonical.as_bytes())
347    }
348}
349
350/// Metadata for a sequence collection (parallel to SequenceMetadata).
351/// Contains the collection digest and level 1 digests for names, sequences, and lengths.
352#[derive(Clone, Debug, Serialize, Deserialize)]
353pub struct SequenceCollectionMetadata {
354    /// Top-level seqcol digest
355    pub digest: String,
356    /// Number of sequences in the collection
357    pub n_sequences: usize,
358    /// Level 1 digest of names array
359    pub names_digest: String,
360    /// Level 1 digest of sequences array
361    pub sequences_digest: String,
362    /// Level 1 digest of lengths array
363    pub lengths_digest: String,
364    /// Ancillary: digest of name_length_pairs array
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub name_length_pairs_digest: Option<String>,
367    /// Ancillary: digest of sorted_name_length_pairs array (order-invariant coordinate system)
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub sorted_name_length_pairs_digest: Option<String>,
370    /// Ancillary: digest of sorted sequences array
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub sorted_sequences_digest: Option<String>,
373    /// Optional path to the source file
374    pub file_path: Option<PathBuf>,
375}
376
377impl SequenceCollectionMetadata {
378    /// Compute metadata from sequence records (core digests only).
379    pub fn from_sequences(
380        sequences: &[SequenceRecord],
381        file_path: Option<PathBuf>,
382    ) -> Self {
383        // Extract metadata refs
384        let metadata_refs: Vec<&SequenceMetadata> =
385            sequences.iter().map(|r| r.metadata()).collect();
386
387        // Compute level 1 digests
388        let lvl1 = SeqColDigestLvl1::from_metadata(&metadata_refs);
389
390        // Compute top-level digest from level 1 digests
391        let digest = lvl1.to_digest();
392
393        Self {
394            digest,
395            n_sequences: sequences.len(),
396            names_digest: lvl1.names_digest,
397            sequences_digest: lvl1.sequences_digest,
398            lengths_digest: lvl1.lengths_digest,
399            name_length_pairs_digest: None,
400            sorted_name_length_pairs_digest: None,
401            sorted_sequences_digest: None,
402            file_path,
403        }
404    }
405
406    /// Compute ancillary digests (name_length_pairs, sorted_name_length_pairs,
407    /// sorted_sequences) from sequence records. No-op if already computed.
408    pub fn compute_ancillary_digests(&mut self, sequences: &[SequenceRecord]) {
409        if self.name_length_pairs_digest.is_some() {
410            return;
411        }
412        let metadata_refs: Vec<&SequenceMetadata> =
413            sequences.iter().map(|r| r.metadata()).collect();
414        self.name_length_pairs_digest =
415            Some(SeqColDigestLvl1::compute_name_length_pairs_digest(&metadata_refs));
416        self.sorted_name_length_pairs_digest =
417            Some(SeqColDigestLvl1::compute_sorted_name_length_pairs_digest(&metadata_refs));
418        self.sorted_sequences_digest =
419            Some(SeqColDigestLvl1::compute_sorted_sequences_digest(&metadata_refs));
420    }
421
422    /// Create from an existing SequenceCollection
423    pub fn from_collection(collection: &SequenceCollection) -> Self {
424        collection.metadata.clone()
425    }
426
427    /// Convert to SeqColDigestLvl1 for compatibility
428    pub fn to_lvl1(&self) -> SeqColDigestLvl1 {
429        SeqColDigestLvl1 {
430            sequences_digest: self.sequences_digest.clone(),
431            names_digest: self.names_digest.clone(),
432            lengths_digest: self.lengths_digest.clone(),
433        }
434    }
435
436    /// Return level 1 representation (attribute digests with spec-compliant field names).
437    pub fn to_level1(&self) -> CollectionLevel1 {
438        CollectionLevel1 {
439            names: self.names_digest.clone(),
440            lengths: self.lengths_digest.clone(),
441            sequences: self.sequences_digest.clone(),
442            name_length_pairs: self.name_length_pairs_digest.clone(),
443            sorted_name_length_pairs: self.sorted_name_length_pairs_digest.clone(),
444            sorted_sequences: self.sorted_sequences_digest.clone(),
445        }
446    }
447}
448
449/// Level 1 representation: attribute digests with spec-compliant JSON field names.
450#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct CollectionLevel1 {
452    pub names: String,
453    pub lengths: String,
454    pub sequences: String,
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub name_length_pairs: Option<String>,
457    #[serde(skip_serializing_if = "Option::is_none")]
458    pub sorted_name_length_pairs: Option<String>,
459    #[serde(skip_serializing_if = "Option::is_none")]
460    pub sorted_sequences: Option<String>,
461}
462
463/// Level 2 representation: full arrays with spec-compliant JSON field names.
464/// Sequences include SQ. prefix per spec.
465#[derive(Debug, Clone, Serialize, Deserialize)]
466pub struct CollectionLevel2 {
467    pub names: Vec<String>,
468    pub lengths: Vec<usize>,
469    /// Sequence digests with SQ. prefix per spec
470    pub sequences: Vec<String>,
471}
472
473/// Result of comparing two sequence collections.
474#[derive(Debug, Clone, Serialize, Deserialize)]
475pub struct SeqColComparison {
476    pub digests: ComparisonDigests,
477    pub attributes: AttributeComparison,
478    pub array_elements: ArrayElementComparison,
479}
480
481/// The digests of the two compared collections.
482/// Either is `None` when that side is an externally-provided level-2 body
483/// with no known digest (serialized as JSON `null`).
484#[derive(Debug, Clone, Serialize, Deserialize)]
485pub struct ComparisonDigests {
486    pub a: Option<String>,
487    pub b: Option<String>,
488}
489
490/// Which attributes (array names) are in A only, B only, or both.
491#[derive(Debug, Clone, Serialize, Deserialize)]
492pub struct AttributeComparison {
493    pub a_only: Vec<String>,
494    pub b_only: Vec<String>,
495    pub a_and_b: Vec<String>,
496}
497
498/// Element-level comparison for each shared attribute.
499#[derive(Debug, Clone, Serialize, Deserialize)]
500pub struct ArrayElementComparison {
501    pub a_count: HashMap<String, usize>,
502    pub b_count: HashMap<String, usize>,
503    pub a_and_b_count: HashMap<String, usize>,
504    pub a_and_b_same_order: HashMap<String, Option<bool>>,
505}
506
507/// Names attached to one sequence digest while matching two collections.
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509pub struct SequenceNameMatch {
510    pub digest: String,
511    pub length: usize,
512    pub names_a: Vec<String>,
513    pub names_b: Vec<String>,
514}
515
516/// Content-based mapping of collection-local sequence names.
517#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518pub struct CollectionNameMatch {
519    pub collection_a: String,
520    pub collection_b: String,
521    pub matches: Vec<SequenceNameMatch>,
522    pub a_only: Vec<SequenceNameMatch>,
523    pub b_only: Vec<SequenceNameMatch>,
524}
525
526/// A single Sequence Collection, which may or may not hold data.
527#[derive(Clone, Debug)]
528pub struct SequenceCollection {
529    /// Collection metadata (digest, level 1 digests, n_sequences, file_path)
530    pub metadata: SequenceCollectionMetadata,
531
532    /// Vector of SequenceRecords, which contain metadata (name, length, digests, alphabet)
533    /// and optionally the actual sequence data.
534    pub sequences: Vec<SequenceRecord>,
535}
536
537impl SequenceCollection {
538    /// Match collection-local names by sequence content digest.
539    ///
540    /// Shared and A-only groups follow collection A's FASTA order; B-only
541    /// groups follow collection B's order. Repeated content is grouped so the
542    /// result naturally represents one-to-many name mappings.
543    pub fn match_sequence_names(&self, other: &Self) -> anyhow::Result<CollectionNameMatch> {
544        use std::collections::{HashMap, HashSet};
545
546        fn groups(collection: &SequenceCollection) -> anyhow::Result<Vec<SequenceNameMatch>> {
547            let mut positions: HashMap<String, usize> = HashMap::new();
548            let mut result: Vec<SequenceNameMatch> = Vec::new();
549            for record in &collection.sequences {
550                let md = record.metadata();
551                if let Some(&index) = positions.get(&md.sha512t24u) {
552                    if result[index].length != md.length {
553                        anyhow::bail!(
554                            "Inconsistent lengths for sequence digest {}: {} and {}",
555                            md.sha512t24u,
556                            result[index].length,
557                            md.length
558                        );
559                    }
560                    result[index].names_a.push(md.name.clone());
561                } else {
562                    positions.insert(md.sha512t24u.clone(), result.len());
563                    result.push(SequenceNameMatch {
564                        digest: md.sha512t24u.clone(),
565                        length: md.length,
566                        names_a: vec![md.name.clone()],
567                        names_b: Vec::new(),
568                    });
569                }
570            }
571            Ok(result)
572        }
573
574        let a_groups = groups(self)?;
575        let b_groups = groups(other)?;
576        let b_by_digest: HashMap<&str, &SequenceNameMatch> = b_groups
577            .iter()
578            .map(|group| (group.digest.as_str(), group))
579            .collect();
580        let mut seen = HashSet::new();
581        let mut matches = Vec::new();
582        let mut a_only = Vec::new();
583        for mut group in a_groups {
584            if let Some(b_group) = b_by_digest.get(group.digest.as_str()) {
585                if group.length != b_group.length {
586                    anyhow::bail!(
587                        "Inconsistent lengths for sequence digest {}: {} and {}",
588                        group.digest,
589                        group.length,
590                        b_group.length
591                    );
592                }
593                group.names_b = b_group.names_a.clone();
594                seen.insert(group.digest.clone());
595                matches.push(group);
596            } else {
597                a_only.push(group);
598            }
599        }
600        let b_only = b_groups
601            .into_iter()
602            .filter(|group| !seen.contains(&group.digest))
603            .map(|group| SequenceNameMatch {
604                names_a: Vec::new(),
605                names_b: group.names_a,
606                digest: group.digest,
607                length: group.length,
608            })
609            .collect();
610        Ok(CollectionNameMatch {
611            collection_a: self.metadata.digest.clone(),
612            collection_b: other.metadata.digest.clone(),
613            matches,
614            a_only,
615            b_only,
616        })
617    }
618
619    /// Create a SequenceCollection from a vector of SequenceRecords.
620    pub fn from_records(records: Vec<SequenceRecord>) -> Self {
621        // Compute metadata from the sequence records (with ancillary digests)
622        let metadata = SequenceCollectionMetadata::from_sequences(&records, None);
623
624        SequenceCollection {
625            metadata,
626            sequences: records,
627        }
628    }
629
630    /// Return level 2 representation (full arrays, spec format).
631    /// Transposes Vec<SequenceRecord> into parallel arrays.
632    pub fn to_level2(&self) -> CollectionLevel2 {
633        let names: Vec<String> = self
634            .sequences
635            .iter()
636            .map(|r| r.metadata().name.clone())
637            .collect();
638        let lengths: Vec<usize> = self.sequences.iter().map(|r| r.metadata().length).collect();
639        let sequences: Vec<String> = self
640            .sequences
641            .iter()
642            .map(|r| format!("SQ.{}", r.metadata().sha512t24u))
643            .collect();
644
645        CollectionLevel2 {
646            names,
647            lengths,
648            sequences,
649        }
650    }
651
652    /// Build the sorted_sequences array as SQ.-prefixed digest strings, sorted lexicographically.
653    pub fn build_sorted_sequences(&self) -> Vec<String> {
654        let mut seqs: Vec<String> = self
655            .sequences
656            .iter()
657            .map(|r| format!("SQ.{}", r.metadata().sha512t24u))
658            .collect();
659        seqs.sort();
660        seqs
661    }
662
663    /// Build the name_length_pairs array as JSON value objects {"length": N, "name": "X"}.
664    /// Keys are in alphabetical order per canonical JSON.
665    pub fn build_name_length_pairs(&self) -> Vec<serde_json::Value> {
666        self.sequences
667            .iter()
668            .map(|r| {
669                let md = r.metadata();
670                let mut obj = serde_json::Map::new();
671                obj.insert(
672                    "length".to_string(),
673                    serde_json::Value::Number(serde_json::Number::from(md.length)),
674                );
675                obj.insert(
676                    "name".to_string(),
677                    serde_json::Value::String(md.name.clone()),
678                );
679                serde_json::Value::Object(obj)
680            })
681            .collect()
682    }
683
684    /// Build the sorted_name_length_pairs array as JSON value objects, sorted by their
685    /// canonical JSON digest.
686    pub fn build_sorted_name_length_pairs(&self) -> Vec<serde_json::Value> {
687        let mut pairs_with_digests: Vec<(String, serde_json::Value)> = self
688            .sequences
689            .iter()
690            .map(|r| {
691                let md = r.metadata();
692                let mut obj = serde_json::Map::new();
693                obj.insert(
694                    "length".to_string(),
695                    serde_json::Value::Number(serde_json::Number::from(md.length)),
696                );
697                obj.insert(
698                    "name".to_string(),
699                    serde_json::Value::String(md.name.clone()),
700                );
701                let val = serde_json::Value::Object(obj);
702                let digest = sha512t24u(canonicalize_json(&val).as_bytes());
703                (digest, val)
704            })
705            .collect();
706        pairs_with_digests.sort_by(|a, b| a.0.cmp(&b.0));
707        pairs_with_digests.into_iter().map(|(_, v)| v).collect()
708    }
709
710    /// Compare this collection with another, following the seqcol spec comparison algorithm.
711    ///
712    /// Dynamically includes ancillary attributes (name_length_pairs, sorted_name_length_pairs,
713    /// sorted_sequences) when present in each collection's metadata.
714    pub fn compare(&self, other: &SequenceCollection) -> SeqColComparison {
715        let arrays_a = self.to_comparison_arrays();
716        let arrays_b = other.to_comparison_arrays();
717        compare_arrays(
718            arrays_a,
719            arrays_b,
720            Some(self.metadata.digest.clone()),
721            Some(other.metadata.digest.clone()),
722        )
723    }
724
725    /// Build string arrays for comparison, including ancillary attributes when present.
726    pub(crate) fn to_comparison_arrays(&self) -> HashMap<String, Vec<String>> {
727        let mut map = HashMap::new();
728
729        // Core 3 are always present
730        map.insert(
731            "names".to_string(),
732            self.sequences.iter().map(|r| r.metadata().name.clone()).collect(),
733        );
734        map.insert(
735            "lengths".to_string(),
736            self.sequences.iter().map(|r| r.metadata().length.to_string()).collect(),
737        );
738        map.insert(
739            "sequences".to_string(),
740            self.sequences.iter().map(|r| format!("SQ.{}", r.metadata().sha512t24u)).collect(),
741        );
742
743        // Ancillary: only include if this collection has them computed
744        if self.metadata.sorted_sequences_digest.is_some() {
745            // sorted_sequences: sort the SQ.-prefixed digests
746            let mut sorted_seqs: Vec<String> = self.sequences
747                .iter()
748                .map(|r| format!("SQ.{}", r.metadata().sha512t24u))
749                .collect();
750            sorted_seqs.sort();
751            map.insert("sorted_sequences".to_string(), sorted_seqs);
752        }
753
754        if self.metadata.name_length_pairs_digest.is_some() {
755            // name_length_pairs: canonical JSON of each {length, name} pair
756            let nlp: Vec<String> = self.sequences
757                .iter()
758                .map(|r| {
759                    let md = r.metadata();
760                    let mut obj = serde_json::Map::new();
761                    obj.insert("length".to_string(), serde_json::Value::Number(serde_json::Number::from(md.length)));
762                    obj.insert("name".to_string(), serde_json::Value::String(md.name.clone()));
763                    canonicalize_json(&serde_json::Value::Object(obj))
764                })
765                .collect();
766            map.insert("name_length_pairs".to_string(), nlp);
767        }
768
769        if self.metadata.sorted_name_length_pairs_digest.is_some() {
770            // sorted_name_length_pairs: digest each pair, sort the digests
771            let mut snlp: Vec<String> = self.sequences
772                .iter()
773                .map(|r| {
774                    let md = r.metadata();
775                    let mut obj = serde_json::Map::new();
776                    obj.insert("length".to_string(), serde_json::Value::Number(serde_json::Number::from(md.length)));
777                    obj.insert("name".to_string(), serde_json::Value::String(md.name.clone()));
778                    sha512t24u(canonicalize_json(&serde_json::Value::Object(obj)).as_bytes())
779                })
780                .collect();
781            snlp.sort();
782            map.insert("sorted_name_length_pairs".to_string(), snlp);
783        }
784
785        map
786    }
787}
788
789/// Compare two arrays element-wise following the seqcol spec.
790/// Returns (overlap_count, same_order).
791///
792/// Port of Python `_compare_elements()`:
793/// - Filter A to elements present in B, filter B to elements present in A
794/// - overlap = min of filtered lengths
795/// - same_order: None if fewer than 2 overlapping elements or unbalanced duplicates,
796///   otherwise filtered_a == filtered_b
797fn compare_elements(a: &[String], b: &[String]) -> (usize, Option<bool>) {
798    use std::collections::HashSet;
799
800    let set_a: HashSet<&str> = a.iter().map(|s| s.as_str()).collect();
801    let set_b: HashSet<&str> = b.iter().map(|s| s.as_str()).collect();
802
803    // Filter each to elements present in the other
804    let filtered_a: Vec<&str> = a.iter().filter(|x| set_b.contains(x.as_str())).map(|s| s.as_str()).collect();
805    let filtered_b: Vec<&str> = b.iter().filter(|x| set_a.contains(x.as_str())).map(|s| s.as_str()).collect();
806
807    let overlap = filtered_a.len().min(filtered_b.len());
808
809    let same_order = if overlap < 2 {
810        None
811    } else if filtered_a.len() != filtered_b.len() || filtered_a.len() != overlap {
812        // Unbalanced duplicates
813        None
814    } else {
815        Some(filtered_a == filtered_b)
816    };
817
818    (overlap, same_order)
819}
820
821/// Core comparison algorithm operating on pre-built attribute array maps.
822/// Used by both `SequenceCollection::compare()` and the external-body comparison path.
823pub(crate) fn compare_arrays(
824    arrays_a: HashMap<String, Vec<String>>,
825    arrays_b: HashMap<String, Vec<String>>,
826    digest_a: Option<String>,
827    digest_b: Option<String>,
828) -> SeqColComparison {
829    let a_keys: std::collections::BTreeSet<&str> = arrays_a.keys().map(|s| s.as_str()).collect();
830    let b_keys: std::collections::BTreeSet<&str> = arrays_b.keys().map(|s| s.as_str()).collect();
831
832    let mut a_only = Vec::new();
833    let mut b_only = Vec::new();
834    let mut a_and_b = Vec::new();
835
836    let mut all_keys: Vec<&str> = a_keys.union(&b_keys).copied().collect();
837    all_keys.sort();
838
839    for key in all_keys {
840        let in_a = a_keys.contains(key);
841        let in_b = b_keys.contains(key);
842        match (in_a, in_b) {
843            (true, true) => a_and_b.push(key.to_string()),
844            (true, false) => a_only.push(key.to_string()),
845            (false, true) => b_only.push(key.to_string()),
846            (false, false) => unreachable!(),
847        }
848    }
849
850    let mut a_count = HashMap::new();
851    let mut b_count = HashMap::new();
852    let mut a_and_b_count = HashMap::new();
853    let mut a_and_b_same_order = HashMap::new();
854
855    for (k, v) in &arrays_a {
856        a_count.insert(k.clone(), v.len());
857    }
858    for (k, v) in &arrays_b {
859        b_count.insert(k.clone(), v.len());
860    }
861
862    for attr in &a_and_b {
863        let arr_a = arrays_a.get(attr).unwrap();
864        let arr_b = arrays_b.get(attr).unwrap();
865        let (overlap, same_order) = compare_elements(arr_a, arr_b);
866        a_and_b_count.insert(attr.clone(), overlap);
867        a_and_b_same_order.insert(attr.clone(), same_order);
868    }
869
870    SeqColComparison {
871        digests: ComparisonDigests {
872            a: digest_a,
873            b: digest_b,
874        },
875        attributes: AttributeComparison {
876            a_only,
877            b_only,
878            a_and_b,
879        },
880        array_elements: ArrayElementComparison {
881            a_count,
882            b_count,
883            a_and_b_count,
884            a_and_b_same_order,
885        },
886    }
887}
888
889/// Turn one attribute of a level-2 JSON body into comparable element strings.
890///
891/// Every element is rendered as canonical JSON (RFC-8785 style, the same
892/// serialization seqcol digests use), so equality matches the refget Python
893/// `compare_seqcols` semantics: `"8"` and `8` differ, objects compare by
894/// content regardless of key order, and `1` equals `1.0`.
895fn level2_json_array(attr: &str, value: &serde_json::Value) -> anyhow::Result<Vec<String>> {
896    let items = value.as_array().ok_or_else(|| {
897        anyhow::anyhow!(
898            "attribute '{}' must be an array in a level-2 seqcol body",
899            attr
900        )
901    })?;
902    Ok(items.iter().map(canonicalize_json).collect())
903}
904
905/// Compare two level-2 sequence collection bodies given as JSON objects.
906///
907/// Neither side needs to be in a store or have a digest: this is the seqcol
908/// spec comparison function applied directly to two level-2 bodies. Every
909/// top-level attribute is compared and must be an array; elements may be
910/// strings, numbers, or objects (e.g. `name_length_pairs`). Elements are
911/// compared by canonical JSON (RFC 8785), so `1` and `1.0` match but `true`
912/// and `1` do not. `digest_a` and
913/// `digest_b` are copied into the result's `digests` field as-is (`None`
914/// becomes JSON `null`).
915///
916/// Returns an error if either body is not a JSON object or holds a
917/// non-array attribute.
918pub fn compare_level2_json(
919    a: &serde_json::Value,
920    b: &serde_json::Value,
921    digest_a: Option<String>,
922    digest_b: Option<String>,
923) -> anyhow::Result<SeqColComparison> {
924    fn to_arrays(
925        side: &str,
926        body: &serde_json::Value,
927    ) -> anyhow::Result<HashMap<String, Vec<String>>> {
928        let obj = body
929            .as_object()
930            .ok_or_else(|| anyhow::anyhow!("seqcol body {} must be a JSON object", side))?;
931        obj.iter()
932            .map(|(k, v)| Ok((k.clone(), level2_json_array(k, v)?)))
933            .collect()
934    }
935    let arrays_a = to_arrays("a", a)?;
936    let arrays_b = to_arrays("b", b)?;
937    Ok(compare_arrays(arrays_a, arrays_b, digest_a, digest_b))
938}
939
940/// Convert a `CollectionLevel2` into the comparison array map format.
941/// Only includes the three core attributes (names, lengths, sequences).
942/// Ancillary attributes are not included because `CollectionLevel2` does not carry them.
943pub(crate) fn level2_to_comparison_arrays(level2: &CollectionLevel2) -> HashMap<String, Vec<String>> {
944    let mut map = HashMap::new();
945    map.insert("names".to_string(), level2.names.clone());
946    map.insert(
947        "lengths".to_string(),
948        level2.lengths.iter().map(|l| l.to_string()).collect(),
949    );
950    map.insert("sequences".to_string(), level2.sequences.clone());
951    map
952}
953
954impl Display for SequenceCollection {
955    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
956        write!(
957            f,
958            "SequenceCollection with {} sequences, digest: {}",
959            self.sequences.len(),
960            self.metadata.digest
961        )?;
962        write!(f, "\nFirst 3 sequences:")?;
963        for seqrec in self.sequences.iter().take(3) {
964            write!(f, "\n- {}", seqrec)?;
965        }
966        Ok(())
967    }
968}
969
970// Iterator implementations for SequenceCollection
971// Allows: for seq in &collection { ... }
972impl<'a> IntoIterator for &'a SequenceCollection {
973    type Item = &'a SequenceRecord;
974    type IntoIter = std::slice::Iter<'a, SequenceRecord>;
975
976    fn into_iter(self) -> Self::IntoIter {
977        self.sequences.iter()
978    }
979}
980
981// Consuming iterator
982// Allows: for seq in collection { ... } (consumes the collection)
983impl IntoIterator for SequenceCollection {
984    type Item = SequenceRecord;
985    type IntoIter = std::vec::IntoIter<SequenceRecord>;
986
987    fn into_iter(self) -> Self::IntoIter {
988        self.sequences.into_iter()
989    }
990}
991
992// ============================================================================
993// Pure computation functions
994// ============================================================================
995
996/// Create a SequenceRecord from raw data, computing all metadata.
997///
998/// This is the sequence-level parallel to `digest_fasta()` for collections.
999/// It computes the GA4GH sha512t24u digest, MD5 digest, detects the alphabet,
1000/// and packages everything into a SequenceRecord with Full variant.
1001///
1002/// # Arguments
1003/// * `name` - The sequence name (e.g., "chr1")
1004/// * `data` - The raw sequence bytes (e.g., b"ACGTACGT")
1005///
1006/// # Returns
1007/// A SequenceRecord::Full with computed metadata and the original data
1008///
1009/// # Example
1010/// ```
1011/// use gtars_refget::digest::types::digest_sequence;
1012///
1013/// let seq = digest_sequence("chr1", b"ACGTACGT");
1014/// assert_eq!(seq.metadata().name, "chr1");
1015/// assert_eq!(seq.metadata().length, 8);
1016/// assert!(!seq.metadata().sha512t24u.is_empty());
1017/// ```
1018pub fn digest_sequence(name: &str, data: &[u8]) -> SequenceRecord {
1019    // Uppercase the data for consistent digest computation (matches FASTA processing)
1020    let uppercased: Vec<u8> = data.iter().map(|b| b.to_ascii_uppercase()).collect();
1021
1022    let metadata = SequenceMetadata {
1023        name: name.to_string(),
1024        description: None,
1025        length: data.len(),
1026        sha512t24u: sha512t24u(&uppercased),
1027        md5: md5(&uppercased),
1028        alphabet: guess_alphabet(&uppercased),
1029        fai: None, // No FAI data for programmatically created sequences
1030    };
1031    SequenceRecord::Full {
1032        metadata,
1033        sequence: Arc::new(uppercased),
1034    }
1035}
1036
1037/// Create a SequenceRecord with a description field.
1038///
1039/// Same as `digest_sequence()` but allows specifying an optional description.
1040///
1041/// # Arguments
1042/// * `name` - The sequence name (e.g., "chr1")
1043/// * `description` - Optional description text
1044/// * `data` - The raw sequence bytes (e.g., b"ACGTACGT")
1045///
1046/// # Returns
1047/// A SequenceRecord::Full with computed metadata and the original data
1048pub fn digest_sequence_with_description(
1049    name: &str,
1050    description: Option<&str>,
1051    data: &[u8],
1052) -> SequenceRecord {
1053    let mut seq = digest_sequence(name, data);
1054    if let SequenceRecord::Full {
1055        ref mut metadata, ..
1056    } = seq
1057    {
1058        metadata.description = description.map(String::from);
1059    }
1060    seq
1061}
1062
1063/// Parse a single RGSI line into SequenceMetadata.
1064///
1065/// Supports two formats:
1066/// - 5-column (no description): `name\tlength\talphabet\tsha512t24u\tmd5`
1067/// - 6-column (with description): `name\tlength\talphabet\tsha512t24u\tmd5\tdescription`
1068///
1069/// Returns None if the line is a comment, empty, or has wrong column count.
1070pub fn parse_rgsi_line(line: &str) -> Option<SequenceMetadata> {
1071    let f = parse_rgsi_fields(line)?;
1072    Some(SequenceMetadata {
1073        name: f.name.to_string(),
1074        description: f.description.map(str::to_string),
1075        length: f.length,
1076        alphabet: f.alphabet,
1077        sha512t24u: f.sha512t24u.to_string(),
1078        md5: f.md5.to_string(),
1079        fai: None,
1080    })
1081}
1082
1083/// The columns of one RGSI line, borrowed from the line (no allocation).
1084pub struct RgsiFields<'a> {
1085    pub name: &'a str,
1086    pub description: Option<&'a str>,
1087    pub length: usize,
1088    pub alphabet: AlphabetType,
1089    pub sha512t24u: &'a str,
1090    pub md5: &'a str,
1091}
1092
1093/// Parse one RGSI line into borrowed fields. Same rules as
1094/// [`parse_rgsi_line`]: 5 or 6 tab-separated columns, empty lines skipped.
1095pub fn parse_rgsi_fields(line: &str) -> Option<RgsiFields<'_>> {
1096    let line = line.strip_suffix('\n').unwrap_or(line);
1097    let line = line.strip_suffix('\r').unwrap_or(line);
1098    if line.trim().is_empty() {
1099        return None;
1100    }
1101    let mut it = line.split('\t');
1102    let name = it.next()?;
1103    let length = it.next()?;
1104    let alphabet = it.next()?;
1105    let sha512t24u = it.next()?;
1106    let md5 = it.next()?;
1107    let description = match it.next() {
1108        None => None,
1109        Some("") => None,
1110        Some(d) => Some(d),
1111    };
1112    if it.next().is_some() {
1113        return None;
1114    }
1115    Some(RgsiFields {
1116        name,
1117        description,
1118        length: length.parse().ok()?,
1119        alphabet: alphabet.parse().unwrap_or(AlphabetType::Unknown),
1120        sha512t24u,
1121        md5,
1122    })
1123}
1124
1125/// Parse a single line from an RGCI (collection index) file.
1126///
1127/// RGCI format is tab-separated with 5+ columns:
1128/// digest, n_sequences, names_digest, sequences_digest, lengths_digest,
1129/// [name_length_pairs_digest, sorted_name_length_pairs_digest, sorted_sequences_digest]
1130///
1131/// Lines starting with '#' are treated as comments and return None.
1132/// Lines with fewer than 5 columns return None.
1133/// Columns 5-7 are optional ancillary digests (empty string = None).
1134pub fn parse_rgci_line(line: &str) -> Option<SequenceCollectionMetadata> {
1135    if line.starts_with('#') {
1136        return None;
1137    }
1138    let parts: Vec<&str> = line.split('\t').collect();
1139    if parts.len() < 5 {
1140        return None;
1141    }
1142    // Parse optional ancillary digest columns (empty string -> None)
1143    let opt_col = |i: usize| -> Option<String> {
1144        parts.get(i).and_then(|s| {
1145            if s.is_empty() { None } else { Some(s.to_string()) }
1146        })
1147    };
1148    Some(SequenceCollectionMetadata {
1149        digest: parts[0].to_string(),
1150        n_sequences: parts[1].parse().ok()?,
1151        names_digest: parts[2].to_string(),
1152        sequences_digest: parts[3].to_string(),
1153        lengths_digest: parts[4].to_string(),
1154        name_length_pairs_digest: opt_col(5),
1155        sorted_name_length_pairs_digest: opt_col(6),
1156        sorted_sequences_digest: opt_col(7),
1157        file_path: None,
1158    })
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn test_metadata() -> Vec<SequenceMetadata> {
1166        vec![
1167            SequenceMetadata {
1168                name: "chrX".to_string(),
1169                description: None,
1170                length: 8,
1171                sha512t24u: "abc123".to_string(),
1172                md5: "md5abc".to_string(),
1173                alphabet: AlphabetType::Dna2bit,
1174                fai: None,
1175            },
1176            SequenceMetadata {
1177                name: "chr1".to_string(),
1178                description: None,
1179                length: 4,
1180                sha512t24u: "def456".to_string(),
1181                md5: "md5def".to_string(),
1182                alphabet: AlphabetType::Dna2bit,
1183                fai: None,
1184            },
1185        ]
1186    }
1187
1188    #[test]
1189    fn test_ancillary_digest_nlp() {
1190        let metadata = test_metadata();
1191        let refs: Vec<&SequenceMetadata> = metadata.iter().collect();
1192        let nlp = SeqColDigestLvl1::compute_name_length_pairs_digest(&refs);
1193        assert!(!nlp.is_empty());
1194        assert_eq!(nlp.len(), 32); // SHA-512/24u is 32 chars base64url
1195    }
1196
1197    #[test]
1198    fn test_ancillary_digest_snlp() {
1199        let metadata = test_metadata();
1200        let refs: Vec<&SequenceMetadata> = metadata.iter().collect();
1201        let snlp = SeqColDigestLvl1::compute_sorted_name_length_pairs_digest(&refs);
1202        assert!(!snlp.is_empty());
1203        assert_eq!(snlp.len(), 32);
1204    }
1205
1206    #[test]
1207    fn test_ancillary_digest_sorted_sequences() {
1208        let metadata = test_metadata();
1209        let refs: Vec<&SequenceMetadata> = metadata.iter().collect();
1210        let ss = SeqColDigestLvl1::compute_sorted_sequences_digest(&refs);
1211        assert!(!ss.is_empty());
1212        assert_eq!(ss.len(), 32);
1213    }
1214
1215    #[test]
1216    fn test_nlp_and_snlp_both_valid() {
1217        let metadata = test_metadata();
1218        let refs: Vec<&SequenceMetadata> = metadata.iter().collect();
1219        let nlp = SeqColDigestLvl1::compute_name_length_pairs_digest(&refs);
1220        let snlp = SeqColDigestLvl1::compute_sorted_name_length_pairs_digest(&refs);
1221        // Both should be valid 32-char digests
1222        assert_eq!(nlp.len(), 32);
1223        assert_eq!(snlp.len(), 32);
1224        // NLP and SNLP may or may not be equal depending on whether pair digests
1225        // are already sorted. The key property is that SNLP is order-invariant
1226        // (tested in test_snlp_order_invariant).
1227    }
1228
1229    #[test]
1230    fn test_snlp_order_invariant() {
1231        let metadata = test_metadata();
1232        // Reverse the order
1233        let reversed: Vec<SequenceMetadata> = metadata.iter().rev().cloned().collect();
1234
1235        let refs1: Vec<&SequenceMetadata> = metadata.iter().collect();
1236        let refs2: Vec<&SequenceMetadata> = reversed.iter().collect();
1237
1238        let snlp1 = SeqColDigestLvl1::compute_sorted_name_length_pairs_digest(&refs1);
1239        let snlp2 = SeqColDigestLvl1::compute_sorted_name_length_pairs_digest(&refs2);
1240
1241        // Sorted NLP should be the same regardless of input order
1242        assert_eq!(snlp1, snlp2);
1243    }
1244
1245    #[test]
1246    fn test_sorted_sequences_order_invariant() {
1247        let metadata = test_metadata();
1248        let reversed: Vec<SequenceMetadata> = metadata.iter().rev().cloned().collect();
1249
1250        let refs1: Vec<&SequenceMetadata> = metadata.iter().collect();
1251        let refs2: Vec<&SequenceMetadata> = reversed.iter().collect();
1252
1253        let ss1 = SeqColDigestLvl1::compute_sorted_sequences_digest(&refs1);
1254        let ss2 = SeqColDigestLvl1::compute_sorted_sequences_digest(&refs2);
1255
1256        // Sorted sequences should be the same regardless of input order
1257        assert_eq!(ss1, ss2);
1258    }
1259
1260    #[test]
1261    fn test_nlp_order_sensitive() {
1262        let metadata = test_metadata();
1263        let reversed: Vec<SequenceMetadata> = metadata.iter().rev().cloned().collect();
1264
1265        let refs1: Vec<&SequenceMetadata> = metadata.iter().collect();
1266        let refs2: Vec<&SequenceMetadata> = reversed.iter().collect();
1267
1268        let nlp1 = SeqColDigestLvl1::compute_name_length_pairs_digest(&refs1);
1269        let nlp2 = SeqColDigestLvl1::compute_name_length_pairs_digest(&refs2);
1270
1271        // Unsorted NLP should differ when order changes
1272        assert_ne!(nlp1, nlp2);
1273    }
1274
1275    #[test]
1276    fn test_to_level1() {
1277        let metadata = test_metadata();
1278        let records: Vec<_> = metadata
1279            .iter()
1280            .map(|m| SequenceRecord::Stub(m.clone()))
1281            .collect();
1282        let mut coll_meta = SequenceCollectionMetadata::from_sequences(&records, None);
1283        coll_meta.compute_ancillary_digests(&records);
1284
1285        let lvl1 = coll_meta.to_level1();
1286        assert_eq!(lvl1.names, coll_meta.names_digest);
1287        assert_eq!(lvl1.lengths, coll_meta.lengths_digest);
1288        assert_eq!(lvl1.sequences, coll_meta.sequences_digest);
1289        assert!(lvl1.name_length_pairs.is_some());
1290        assert!(lvl1.sorted_name_length_pairs.is_some());
1291        assert!(lvl1.sorted_sequences.is_some());
1292    }
1293
1294    #[test]
1295    fn test_to_level2() {
1296        let metadata = test_metadata();
1297        let records: Vec<SequenceRecord> = metadata
1298            .iter()
1299            .map(|m| SequenceRecord::Stub(m.clone()))
1300            .collect();
1301        let collection = SequenceCollection::from_records(records);
1302
1303        let lvl2 = collection.to_level2();
1304        assert_eq!(lvl2.names, vec!["chrX", "chr1"]);
1305        assert_eq!(lvl2.lengths, vec![8, 4]);
1306        assert_eq!(lvl2.sequences.len(), 2);
1307        assert!(lvl2.sequences[0].starts_with("SQ."));
1308    }
1309
1310    #[test]
1311    fn test_compare_same() {
1312        let records: Vec<SequenceRecord> = test_metadata().into_iter().map(SequenceRecord::Stub).collect();
1313        let collection = SequenceCollection::from_records(records);
1314        let result = collection.compare(&collection);
1315
1316        assert_eq!(result.digests.a, result.digests.b);
1317        assert_eq!(result.attributes.a_and_b.len(), 3); // core only, no ancillary
1318        for attr in &result.attributes.a_and_b {
1319            assert_eq!(result.array_elements.a_and_b_same_order[attr], Some(true));
1320        }
1321    }
1322
1323    #[test]
1324    fn test_compare_reversed_order() {
1325        let metadata = test_metadata();
1326        let reversed: Vec<SequenceMetadata> = metadata.iter().rev().cloned().collect();
1327        let coll_a = SequenceCollection::from_records(metadata.into_iter().map(SequenceRecord::Stub).collect());
1328        let coll_b = SequenceCollection::from_records(reversed.into_iter().map(SequenceRecord::Stub).collect());
1329
1330        let result = coll_a.compare(&coll_b);
1331        for attr in &result.attributes.a_and_b {
1332            assert_eq!(result.array_elements.a_and_b_count[attr], 2);
1333            assert_eq!(result.array_elements.a_and_b_same_order[attr], Some(false));
1334        }
1335    }
1336
1337    #[test]
1338    fn test_compare_single_element() {
1339        let meta = SequenceMetadata {
1340            name: "chr1".to_string(),
1341            description: None,
1342            length: 4,
1343            sha512t24u: "abc".to_string(),
1344            md5: "md5".to_string(),
1345            alphabet: AlphabetType::Dna2bit,
1346            fai: None,
1347        };
1348        let coll = SequenceCollection::from_records(vec![SequenceRecord::Stub(meta)]);
1349        let result = coll.compare(&coll);
1350
1351        // With only 1 element overlap, same_order should be None
1352        for attr in &result.attributes.a_and_b {
1353            assert_eq!(result.array_elements.a_and_b_same_order[attr], None);
1354        }
1355    }
1356
1357    #[test]
1358    fn test_match_sequence_names_groups_duplicates_preserves_order_and_reports_unmatched() {
1359        let a = SequenceCollection::from_records(vec![
1360            digest_sequence("chr2L", b"ACGT"),
1361            digest_sequence("chr2L_copy", b"ACGT"),
1362            digest_sequence("chr3", b"GGCC"),
1363            digest_sequence("chr4", b"CCCC"),
1364        ]);
1365        let b = SequenceCollection::from_records(vec![
1366            digest_sequence("4", b"CCCC"),
1367            digest_sequence("2L", b"ACGT"),
1368            digest_sequence("2L_alt", b"ACGT"),
1369            digest_sequence("extra", b"TTAA"),
1370        ]);
1371
1372        let result = a.match_sequence_names(&b).unwrap();
1373
1374        assert_eq!(result.matches.len(), 2);
1375        assert_eq!(result.matches[0].digest, sha512t24u(b"ACGT"));
1376        assert_eq!(result.matches[0].names_a, ["chr2L", "chr2L_copy"]);
1377        assert_eq!(result.matches[0].names_b, ["2L", "2L_alt"]);
1378        assert_eq!(result.matches[1].digest, sha512t24u(b"CCCC"));
1379        assert_eq!(result.matches[1].names_a, ["chr4"]);
1380        assert_eq!(result.matches[1].names_b, ["4"]);
1381        assert_eq!(result.a_only.len(), 1);
1382        assert_eq!(result.a_only[0].digest, sha512t24u(b"GGCC"));
1383        assert_eq!(result.a_only[0].names_a, ["chr3"]);
1384        assert_eq!(result.b_only.len(), 1);
1385        assert_eq!(result.b_only[0].digest, sha512t24u(b"TTAA"));
1386        assert_eq!(result.b_only[0].names_b, ["extra"]);
1387    }
1388}