use std::{
    fmt::Write,
    fs::{self},
    path::Path,
};

fn main() {
    // Tell Cargo that if the given file changes, to rerun this build script.
    println!("cargo::rerun-if-changed=tests/simulation");

    let Ok(paths) = fs::read_dir("tests/simulation") else {
        return;
    };

    let mut modules = Vec::new();

    for path in paths {
        let Ok(path) = path else {
            continue;
        };
        let path = path.path();
        if path.extension().is_none_or(|ext| ext != "rs") {
            continue;
        }
        let mod_name = path.with_extension("");
        let mod_name = mod_name.file_name().unwrap().to_string_lossy().to_string();
        if mod_name == "mod" {
            continue;
        }
        modules.push(mod_name);
    }

    let mut mod_rs = String::new();

    mod_rs.push_str("// This file is @generated by `azalea-client/build.rs`.\n\n");
    modules.sort();
    for mod_name in modules {
        let _ = writeln!(mod_rs, "mod {mod_name};");
    }

    let mod_rs_path = Path::new("tests/simulation/mod.rs");

    let existing_mod_rs = fs::read_to_string(mod_rs_path).unwrap_or_default();
    if mod_rs.trim() == existing_mod_rs.trim() {
        // this would cause the build script to run again
        return;
    }
    let _ = fs::write(mod_rs_path, mod_rs);
}
