//! Build script.
//!
//! Reads `.env` and bakes any `POLYMODEL_*` variables into `src/env.rs` as
//! compile-time constants. This is how configuration reaches the WASM bundle,
//! which has no filesystem or process environment to read at runtime.
//!
//! Server-side runtime configuration (DATABASE_URL, HYDRANT_*) is NOT handled
//! here: the server binary loads `.env` directly via `dotenvy` and reads it into
//! a typed `ServerConfig` struct (see `src/indexing/config.rs`).

use std::env;
use std::fs::File;
use std::io::Write;

fn main() {
    println!("cargo:rerun-if-changed=.env");

    dotenvy::dotenv().ok();

    let mut f = File::create("./src/env.rs").expect("create src/env.rs");
    f.write_all(
        b"// This file is automatically generated by build.rs.\n\
          // Frontend (WASM) compile-time configuration.\n\
          // Do not edit; regenerate by rebuilding.\n\n",
    )
    .expect("write env.rs header");

    // Bake every POLYMODEL_* env var into the bundle as a `&'static str` const.
    for (key, value) in env::vars() {
        if let Some(rest) = key.strip_prefix("POLYMODEL_") {
            if rest.is_empty() {
                continue;
            }
            let line = format!(
                "#[allow(unused)]\npub const {}: &str = \"{}\";\n",
                key,
                value.replace('\\', "\\\\").replace('"', "\\\"")
            );
            f.write_all(line.as_bytes()).expect("write env.rs const");
        }
    }
}
