use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use anyhow::{anyhow, Context, Result};
use serde::Deserialize;
use crate::transcripts::models::{Exon, ManeStatus, Strand, Transcript};
use crate::transcripts::store::build_reftx_bytes;
const READ_BUFFER_SIZE: usize = 256 * 1024;
#[derive(Deserialize)]
struct CdotTranscript {
id: String,
gene_name: Option<String>,
contig: String,
strand: i8,
cds_start: Option<u32>,
cds_end: Option<u32>,
exons: Vec<(u32, u32)>,
}
#[derive(Deserialize)]
struct CdotFile {
transcripts: HashMap<String, CdotTranscript>,
}
pub struct TxStoreBuilder {
pub transcripts: Vec<Transcript>,
chrom_to_digest: HashMap<String, [u8; 24]>,
mane_flags: HashMap<String, u8>,
}
impl TxStoreBuilder {
pub fn new() -> Self {
Self {
transcripts: Vec::new(),
chrom_to_digest: HashMap::new(),
mane_flags: HashMap::new(),
}
}
pub fn load_mane_summary<P: AsRef<Path>>(&mut self, path: P) -> Result<usize> {
let file = File::open(path.as_ref())?;
let reader: Box<dyn BufRead> = if path.as_ref().extension().is_some_and(|e| e == "gz") {
Box::new(BufReader::new(flate2::read::GzDecoder::new(file)))
} else {
Box::new(BufReader::new(file))
};
let mut lines = reader.lines();
let header = loop {
let line = lines
.next()
.ok_or_else(|| anyhow!("MANE summary is empty"))??;
if !line.is_empty() {
break line;
}
};
let columns: Vec<&str> = header.trim_start_matches('#').split('\t').collect();
let refseq_idx = columns
.iter()
.position(|c| c.trim() == "RefSeq_nuc")
.ok_or_else(|| anyhow!("RefSeq_nuc column not found in MANE summary"))?;
let ensembl_idx = columns
.iter()
.position(|c| c.trim() == "Ensembl_nuc")
.ok_or_else(|| anyhow!("Ensembl_nuc column not found in MANE summary"))?;
let status_idx = columns
.iter()
.position(|c| c.trim() == "MANE_status")
.ok_or_else(|| anyhow!("MANE_status column not found in MANE summary"))?;
let mut count = 0;
for line in lines {
let line = line?;
if line.is_empty() || line.starts_with('#') {
continue;
}
let fields: Vec<&str> = line.split('\t').collect();
let max_idx = status_idx.max(refseq_idx).max(ensembl_idx);
if fields.len() <= max_idx {
continue;
}
let flags = match fields[status_idx].trim() {
"MANE Select" => 0x01,
"MANE Plus Clinical" => 0x03,
_ => continue,
};
for &raw in &[fields[refseq_idx], fields[ensembl_idx]] {
let acc = raw.trim();
if acc.is_empty() {
continue;
}
self.mane_flags.insert(acc.to_string(), flags);
if let Some((base, _)) = acc.split_once('.') {
self.mane_flags.insert(base.to_string(), flags);
}
count += 1;
}
}
Ok(count)
}
#[inline]
pub fn has_mane_flags(&self) -> bool {
!self.mane_flags.is_empty()
}
pub fn add_chrom_mapping(&mut self, name: &str, digest: [u8; 24]) {
self.chrom_to_digest.insert(name.to_string(), digest);
}
pub fn ingest_cdot<P: AsRef<Path>>(&mut self, path: P) -> Result<usize> {
let file = File::open(path.as_ref())?;
let reader: Box<dyn std::io::Read> =
if path.as_ref().extension().is_some_and(|e| e == "gz") {
Box::new(flate2::read::GzDecoder::new(BufReader::with_capacity(
READ_BUFFER_SIZE,
file,
)))
} else {
Box::new(BufReader::with_capacity(READ_BUFFER_SIZE, file))
};
let cdot: CdotFile = serde_json::from_reader(reader)?;
let mut count = 0;
for (_, tx) in cdot.transcripts {
let chrom_digest = match self.chrom_to_digest.get(&tx.contig) {
Some(d) => *d,
None => continue,
};
let strand = match tx.strand {
1 => Strand::Forward,
-1 => Strand::Reverse,
_ => continue,
};
let exons: Vec<Exon> = tx
.exons
.into_iter()
.map(|(s, e)| Exon { start: s, end: e })
.collect();
if exons.is_empty() {
continue;
}
let mane_flag_byte = self
.mane_flags
.get(&tx.id)
.copied()
.or_else(|| {
let base = tx.id.split('.').next().unwrap_or(&tx.id);
self.mane_flags.get(base).copied()
})
.unwrap_or(0);
self.transcripts.push(Transcript {
accession: tx.id,
gene: tx.gene_name.unwrap_or_default(),
chrom_digest,
strand,
cds_start: tx.cds_start,
cds_end: tx.cds_end,
exons,
mane: ManeStatus::from_flags_byte(mane_flag_byte),
});
count += 1;
}
Ok(count)
}
pub fn len(&self) -> usize {
self.transcripts.len()
}
pub fn is_empty(&self) -> bool {
self.transcripts.is_empty()
}
pub fn build<P: AsRef<Path>>(&mut self, output: P) -> Result<()> {
if self.transcripts.is_empty() {
return Err(anyhow!("No transcripts to write"));
}
let dest = output.as_ref();
let _lock = BuildLock::acquire(dest)?;
let bytes = build_reftx_bytes(&self.transcripts)?;
crate::store::atomic::atomic_write_bytes(dest, &bytes)
.with_context(|| format!("failed to atomically publish {:?}", dest))
}
}
struct BuildLock {
path: PathBuf,
}
impl BuildLock {
fn acquire(dest: &Path) -> Result<Self> {
let mut path = dest.as_os_str().to_os_string();
path.push(".lock");
let path = PathBuf::from(path);
OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.with_context(|| {
format!(
"acquiring build lock {:?} (another builder may be running)",
path
)
})?;
Ok(Self { path })
}
}
impl Drop for BuildLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
impl Default for TxStoreBuilder {
fn default() -> Self {
Self::new()
}
}