use std::{fs, io::BufReader, path::Path};

use anyhow::{Context, Result};
use pimcore::json_to_instruction::json_to_executor;
use serde_json::Value;

fn collect_json_from_subfolders<P: AsRef<Path>>(root: P) -> Result<Vec<(Value, Vec<Value>)>> {
    let mut result = Vec::new();
    for entry in fs::read_dir(root)? {
        let entry = entry.context("Root not found")?;
        let path = entry.path();
        if path.is_dir() {
            let mut cores = Vec::new();
            let mut config: Option<Value> = None;
            for sub_entry in fs::read_dir(&path)
                .with_context(|| format!("File {} not readable", path.display()))?
            {
                let sub_entry =
                    sub_entry.with_context(|| format!("File {} not readable", path.display()))?;
                let sub_path = sub_entry.path();
                if sub_path.is_file()
                    && sub_path.extension().and_then(|s| s.to_str()) == Some("json")
                {
                    let file = fs::File::open(&sub_path)
                        .with_context(|| format!("Subpath  {} not opened", sub_path.display()))?;
                    let reader = BufReader::new(file);
                    let val: Value = serde_json::from_reader(reader).with_context(|| format!(
                        "Serde reader fail for subpath {}",
                        sub_path.display()
                    ))?;
                    if sub_path.file_name().unwrap() == "config.json" {
                        config = Some(val);
                    } else {
                        cores.push(val);
                    }
                }
            }
            result.push((config.unwrap(), cores));
        }
    }
    Ok(result)
}

#[test]
fn json_folder_tester() {
    let examples = collect_json_from_subfolders("data").unwrap();
    for example in examples {
        let (config, cores) = example;
        json_to_executor::json_to_executor(config, cores.iter()).execute();
    }
}
