use std::io::{self, BufWriter};
use std::path::PathBuf;

use clap::Args;
use obikindex::KmerIndex;
use obikseq::set_k;
use tracing::info;

#[derive(Args)]
pub struct DumpArgs {
    /// Index directory to dump
    pub index: PathBuf,

    /// Output presence/absence (0/1) even if the index stores counts
    #[arg(long, default_value_t = false)]
    pub force_presence: bool,

    /// Prepend partition and layer columns to each row
    #[arg(long, default_value_t = false)]
    pub debug: bool,
}

pub fn run(args: DumpArgs) {
    let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
        eprintln!("error opening index: {e}");
        std::process::exit(1);
    });

    set_k(idx.kmer_size());
    info!(
        "dumping {} partitions, {} genome(s)",
        idx.n_partitions(),
        idx.meta().genomes.len()
    );

    let stdout = io::stdout();
    let mut out = BufWriter::new(stdout.lock());

    idx.dump(&mut out, args.force_presence, args.debug).unwrap_or_else(|e| {
        eprintln!("dump error: {e}");
        std::process::exit(1);
    });
}
