use std::path::{Path, PathBuf};

use bone_jig::{RunResult, Scenario, ScenarioSource, run_scenario};

#[must_use]
pub fn manifest_path(rel: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(rel)
}

#[must_use]
pub fn run_library_scenario(name: &str, out_dir: &Path) -> RunResult {
    let source = ScenarioSource::Path(manifest_path(&format!("scenarios/{name}")));
    let scenario = match Scenario::load(&source) {
        Ok(s) => s,
        Err(e) => panic!("load {name}: {e}"),
    };
    let mut sink = Vec::new();
    match run_scenario(&scenario, out_dir, &mut sink) {
        Ok(result) => result,
        Err(e) => panic!("run {name}: {e}"),
    }
}

#[must_use]
pub fn find_artifact(out_dir: &Path, suffix: &str) -> PathBuf {
    let entries = match std::fs::read_dir(out_dir) {
        Ok(it) => it,
        Err(e) => panic!("read {}: {e}", out_dir.display()),
    };
    entries
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .find(|path| {
            path.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.ends_with(suffix))
        })
        .unwrap_or_else(|| panic!("no artifact ending in {suffix} under {}", out_dir.display()))
}
