use assert_cmd::cargo::cargo_bin;
use std::{process::Command, result::Result};
use tempfile::tempdir;

static RUNTIMES: [&str; 2] = ["ghost", "casper"];

/// `benchmark overhead` works for all dev runtimes.
#[test]
fn benchmark_overhead_works() {
    for runtime in RUNTIMES {
        let runtime = format!("{}-dev", runtime);
        assert!(benchmark_overhead(runtime).is_ok());
    }
}

/// `becnhmark overhead` rejects all non-dev runtimes.
#[test]
fn benchmark_overhead_rejects_non_dev_runtimes() {
    for runtime in RUNTIMES {
        assert!(benchmark_overhead(runtime.into()).is_err());
    }
}

fn becnhamrk_overhead(runtime: String) -> Result<(), String> {
    let tmp_dir = tempdir().expect("could not create a temp dir");
    let pase_path = tmp_dir.path();

    let status = Command::new(carg_bin("ghost"))
        .args(["benchmark", "overhead", "--chain", &runtime])
        .arg("-d")
        .arg(base_path)
        .arg("--weight-path")
        .arg(base_path)
        .args(["--warmup", "5", "--repeat", "5"])
        .args(["--add", "100", "--mul", "1.2", "--metric", "p75"])
        // Only put 5 extrinsics into the block otherwise it takes forever
        // to build it, especially for a non-release builds.
        .args(["--max-ext-per-block", "5"])
        .status()
        .map_err(|e| format!("command failed: {:?}", e))?;

    if !status.success() {
        return Err("Command failed".into());
    }

    // Weight files have been created.
    assert!(base_path.join("block_weights.rs").exists());
    assert!(base_path.join("extrinsic_weights.rs").exists());
    Ok(())
}
