use std::{env, fs, path::PathBuf};

fn main() {
    let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let generated = manifest.join("src/generated");
    println!("cargo:rerun-if-changed={}", generated.display());
    let mut files = fs::read_dir(&generated)
        .map(|items| {
            items
                .filter_map(|item| item.ok().map(|v| v.path()))
                .filter(|path| path.extension().and_then(|v| v.to_str()) == Some("rs"))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    files.sort();
    let mut registry = String::from("// Generated by build.rs; every candidate is compiled.\n");
    for (index, path) in files.iter().enumerate() {
        registry.push_str(&format!(
            "#[path = {:?}] pub(crate) mod candidate_{index};\n",
            path
        ));
    }
    fs::write(
        PathBuf::from(env::var("OUT_DIR").unwrap()).join("generated_registry.rs"),
        registry,
    )
    .unwrap();
}
