fn main() {
    let hash = std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .unwrap_or_default();
    let hash = hash.trim();
    println!("cargo:rustc-env=GIT_COMMIT={}", if hash.is_empty() { "unknown" } else { hash });
    println!("cargo:rerun-if-changed=.git/HEAD");

    // Embed Windows icon when cross-compiling for Windows
    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
        // Find windres: prefer arch-prefixed, fall back to plain windres
        let windres = if std::process::Command::new("x86_64-w64-mingw32-windres")
            .arg("--version")
            .output()
            .is_ok()
        {
            "x86_64-w64-mingw32-windres"
        } else {
            "windres"
        };

        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let out_dir = std::env::var("OUT_DIR").unwrap();

        let mut res = winres::WindowsResource::new();
        res.set_icon(&format!("{}/../../assets/icon.ico", manifest_dir));
        res.set_toolkit_path("/usr");
        res.set_windres_path(windres);
        res.set_ar_path("x86_64-w64-mingw32-ar");

        match res.compile() {
            Ok(_) => {
                println!("cargo:warning=Icon embedded successfully via {windres}");
                // Pass resource.o directly as linker arg (avoids ld skipping unreferenced archive members)
                println!("cargo:rustc-link-arg={}/resource.o", out_dir);
            }
            Err(e) => {
                println!("cargo:warning=winres failed: {e}");
                println!("cargo:warning=windres path used: {windres}");
            }
        }
    }
}
