use std::{path::PathBuf, process::Output, str::FromStr as _};

use assert_cmd::cargo;

const REFERENCE_PATH: &str = "tests/data/reference";

fn reference_path() -> Option<PathBuf> {
    let data_dir = PathBuf::from_str(REFERENCE_PATH).unwrap();
    if data_dir.exists() {
        for file in data_dir.read_dir().unwrap() {
            let file = file.unwrap().path();
            if file.to_str().unwrap().ends_with(".fa.gz") {
                return Some(file);
            }
        }
    }
    None
}

pub fn ref_path() -> String {
    let Some(path) = reference_path() else {
        panic!(
            "Reference not found. You can download the reference file by running `bash ./cli/tests/download_reference.sh`.",
        );
    };
    path.to_str().unwrap().to_string()
}

pub fn twitcher_with_ref(additional_args: &str) -> Output {
    let fa = ref_path();
    let mut args = vec!["vcf", "--reference", &fa];
    args.extend(additional_args.split_whitespace());
    let mut cmd = cargo::cargo_bin_cmd!("twitcher");
    cmd.args(args);
    cmd.unwrap()
}

#[allow(unused)]
pub fn twitcher(args: &str) -> Output {
    let mut cmd = cargo::cargo_bin_cmd!("twitcher");
    cmd.args(args.split_whitespace());
    cmd.unwrap()
}
