use std::env;
use std::fs;
use std::path::Path;

fn main() {
    // Only run compression when embed-configs feature is enabled
    if env::var("CARGO_FEATURE_EMBED_CONFIGS").is_ok() {
        compress_configs();
    }
}

fn compress_configs() {
    // Simpler build-time generation: scan `share/` and generate a small Rust
    // source file (`embedded_configs.rs`) with a `pub const EMBEDDED_CONFIGS`.
    // This avoids hard-coding and doesn't require external crates or compression.
    println!("cargo:rerun-if-changed=share/");

    let out_dir = env::var("OUT_DIR").unwrap();
    let embedded_path = Path::new(&out_dir).join("embedded_configs.rs");

    let mut config_files: Vec<String> = Vec::new();
    if let Ok(entries) = fs::read_dir("share") {
        for entry in entries.filter_map(|e| e.ok()) {
            if let Ok(ft) = entry.file_type()
                && !ft.is_file()
            {
                continue;
            }
            if let Ok(name) = entry.file_name().into_string()
                && name.starts_with("conf.")
            {
                config_files.push(name);
            }
        }
    }

    config_files.sort();

    let mut embedded_output = String::new();
    embedded_output.push_str("/// Embedded configuration files compiled into the binary when the `embed-configs` feature is enabled.\n");
    embedded_output.push_str("/// Each entry is a tuple of `(filename, contents)` corresponding to files under `share/conf.*`.\n");
    embedded_output.push_str("/// This file is generated by build.rs — do not edit.\n");
    embedded_output.push_str("pub const EMBEDDED_CONFIGS: &[(&str, &str)] = &[\n");

    for f in &config_files {
        // Use include_str! anchored to the manifest dir so the files are included
        // from the workspace path at compile-time.
        embedded_output.push_str(&format!(
            "    (\"{}\", include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/share/{}\"))),\n",
            f, f
        ));
    }

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

    // Also generate a small list of embedded file names to make testing/debugging easier
    embedded_output.push_str("/// Names of the embedded config files (sorted)\n");
    embedded_output.push_str("pub const EMBEDDED_CONFIG_NAMES: &[&str] = &[\n");
    for f in &config_files {
        embedded_output.push_str(&format!("    \"{}\",\n", f));
    }
    embedded_output.push_str("];\n");

    fs::write(&embedded_path, embedded_output).unwrap();
    println!(
        "cargo:rustc-env=EMBEDDED_CONFIGS_PATH={}",
        embedded_path.display()
    );
}
