use std::{fs::File, io::{BufRead, BufReader, Write}};

use anyhow::Context;
use bgzip::{write::BGZFMultiThreadWriter, Compression};
use log::{info, warn};

use crate::variant::variant::VcfVariant;

use super::readers::get_reader;

pub fn read_vcf(path: &str) -> anyhow::Result<Vec<VcfVariant>> {
    let reader = BufReader::new(get_reader(path)?);

    let mut res = Vec::new();
    for (i, line) in reader.lines().enumerate() {
        match line {
            Ok(line) => {
                if line.starts_with("#") {
                    continue;
                }
                res.push(line.parse().context(format!("Can't parse {line}"))?);
            }
            Err(e) => warn!("Can't read line {i}: {e}"),
        }
    }

    Ok(res)
}

pub fn write_vcf(variants: &[VcfVariant], path: &str) -> anyhow::Result<()> {
    info!("Writing: {path}");
    let file = File::create(path)?;
    let mut writer = BGZFMultiThreadWriter::new(file, Compression::default());
    writer.write_all(b"##fileformat=VCFv4.2\n")?;
    writer.write_all(b"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n")?;

    for variant in variants {
        writer.write_fmt(format_args!("{}\n", variant.commun_deepvariant_clairs().into_vcf_row()))?;
    }

    writer.close()?;
    Ok(())
}


