use std::path::Path;

use crate::{
    cdr, guess, json, tariff,
    test::{self, read_file_content},
    Versioned as _,
};

#[test_each::file(
    glob = "ocpi-tariffs/test_data/v221/real_world/*/cdr*.json",
    name(segments = 2)
)]
fn should_guess_version_v221(cdr_json: &str, path: &Path) {
    test::setup();

    test_guess(crate::Version::V221, cdr_json, path);
}

#[test_each::file(glob = "ocpi-tariffs/test_data/v211/*/cdr*.json", name(segments = 2))]
fn should_guess_version_v211(cdr_json: &str, path: &Path) {
    test::setup();

    test_guess(crate::Version::V211, cdr_json, path);
}

#[track_caller]
fn test_guess(expected_version: crate::Version, cdr_json: &str, path: &Path) {
    {
        let mut cdr_json = cdr_json.to_owned();
        json_strip_comments::strip(&mut cdr_json).unwrap();
        let cdr = json::parse_object(&cdr_json).unwrap();
        let cdr_guess = cdr::infer_version(cdr);

        let guess::Version::Certain(cdr) = cdr_guess else {
            panic!("expected a certain version, got {cdr_guess:?}");
        };
        assert_eq!(cdr.version(), expected_version);
    }

    {
        let tariff_json = read_file_content(&path.parent().unwrap().join("tariff.json")).ok();

        if let Some(json) = tariff_json {
            let tariff = json::parse_object(&json).unwrap();
            let tariff_guess = tariff::infer_version(tariff);

            let guess::Version::Certain(tariff) = tariff_guess else {
                panic!("expected a certain version, got {tariff_guess:?}");
            };
            assert_eq!(tariff.version(), expected_version);
        }
    }
}
