use std::env;
use std::fs;
use std::path::PathBuf;

fn main() {
    println!("cargo:rerun-if-changed=assets/i18n");
    println!(
        "cargo:rustc-env=GTC_TARGET_TRIPLE={}",
        env::var("TARGET").expect("TARGET")
    );

    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("manifest dir"));
    let i18n_dir = manifest_dir.join("assets").join("i18n");

    let mut locales = Vec::new();
    if let Ok(entries) = fs::read_dir(&i18n_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_file() {
                continue;
            }
            let Some(file_name) = path.file_name().and_then(|v| v.to_str()) else {
                continue;
            };
            if file_name == "locales.json" || !file_name.ends_with(".json") {
                continue;
            }
            let locale = file_name.trim_end_matches(".json").to_string();
            locales.push(locale);
        }
    }

    locales.sort();

    let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
    let out_file = out_dir.join("embedded_i18n.rs");

    let mut generated = String::new();
    generated.push_str("// @generated by build.rs\n");
    generated.push_str("const EMBEDDED_LOCALES: &[(&str, &str)] = &[\n");

    for locale in locales {
        let path = format!("/assets/i18n/{locale}.json");
        generated.push_str(&format!(
            "    (\"{locale}\", include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"{path}\"))),\n"
        ));
    }

    generated.push_str("];\n");

    fs::write(out_file, generated).expect("write embedded_i18n.rs");
}
