// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
// SPDX-License-Identifier: BSD-2-Clause
//! Load the test definitions.

use std::fs;

use anyhow::{bail, Context as _, Result};
use camino::Utf8Path;
use tracing::debug;

use crate::defs::TestData;

const PATH_TESTS: &str = "tests/test-data/tests.json";

/// Load the test definitions from the JSON file.
pub fn load_defs() -> Result<TestData> {
    let test_defs = Utf8Path::new(PATH_TESTS)
        .canonicalize_utf8()
        .with_context(|| format!("Could not canonicalize the test defs path {PATH_TESTS}"))?;
    debug!("about to read {test_defs}");
    let contents = fs::read_to_string(&test_defs)
        .with_context(|| format!("Could not read the test definitions from {test_defs}"))?;
    let fver = typed_format_version::get_version_from_str(&contents, serde_json::from_str)
        .with_context(|| format!("Could not get the format version from {test_defs}"))?;
    if (fver.major(), fver.minor()) != (0, 1) {
        bail!(format!(
            "Unexpected test definitions format version {major}.{minor}",
            major = fver.major(),
            minor = fver.minor()
        ));
    }

    serde_json::from_str::<TestData>(&contents)
        .with_context(|| format!("Could not load the test definitions from {test_defs}"))
}
