use std::path::PathBuf;
use std::process::Command;

fn main() {
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    // Workspace root is two levels up from crates/ahfail-display/
    let workspace_root = manifest_dir.join("../..").canonicalize().unwrap();
    let assets_dir = workspace_root.join("assets");
    let gresource_xml = assets_dir.join("ahfail.gresource.xml");

    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
    let c_src = out_dir.join("ahfail-resources.c");

    // Re-run if any asset changes
    println!("cargo:rerun-if-changed={}", gresource_xml.display());
    for entry in std::fs::read_dir(&assets_dir).unwrap() {
        let entry = entry.unwrap();
        println!("cargo:rerun-if-changed={}", entry.path().display());
    }

    let status = Command::new("glib-compile-resources")
        .args([
            "--generate-source",
            "--target",
            c_src.to_str().unwrap(),
            "--sourcedir",
            assets_dir.to_str().unwrap(),
            gresource_xml.to_str().unwrap(),
        ])
        .status()
        .expect("glib-compile-resources not found — install libglib2.0-dev or equivalent");

    assert!(status.success(), "glib-compile-resources failed");

    // Use pkg-config to get include flags for gio-2.0
    let gio_cflags = Command::new("pkg-config")
        .args(["--cflags", "gio-2.0"])
        .output()
        .expect("pkg-config not found");
    assert!(gio_cflags.status.success(), "pkg-config --cflags gio-2.0 failed");
    let gio_cflags_str = String::from_utf8(gio_cflags.stdout).unwrap();

    let mut build = cc::Build::new();
    build.file(&c_src).flag_if_supported("-w"); // suppress warnings in generated code
    for flag in gio_cflags_str.split_whitespace() {
        build.flag(flag);
    }
    build.compile("ahfail_resources");

    // Link against gio-2.0 for GResource support
    println!("cargo:rustc-link-lib=gio-2.0");
}
