//! Build-script that compiles the Blueprint UI files into GtkBuilder
//! XML, then bundles them (plus icons / CSS) into a single
//! GResource blob the binary slurps via `include_bytes!`.
//!
//! Using build.rs (instead of meson driving cargo) keeps "just run
//! `cargo build`" working for developers. Meson, when we add it
//! for the Flatpak workflow, will simply wrap cargo and inherit
//! all this — no duplication.

use std::path::{Path, PathBuf};
use std::process::Command;

fn main() {
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());

    let ui_src = manifest_dir.join("data/ui");
    let ui_out = out_dir.join("ui");
    std::fs::create_dir_all(&ui_out).expect("mkdir ui out");

    // 1. Compile every .blp under data/ui/ → $OUT_DIR/ui/*.ui
    for entry in std::fs::read_dir(&ui_src).expect("read data/ui") {
        let path = entry.expect("dirent").path();
        if path.extension().and_then(|s| s.to_str()) != Some("blp") {
            continue;
        }
        let stem = path.file_stem().unwrap().to_str().unwrap();
        let target = ui_out.join(format!("{stem}.ui"));
        println!("cargo:rerun-if-changed={}", path.display());
        run(
            Command::new("blueprint-compiler")
                .arg("compile")
                .arg("--output")
                .arg(&target)
                .arg(&path),
            &format!("blueprint-compiler {stem}.blp"),
        );
    }

    // 2. Copy the GResource manifest into $OUT_DIR so its relative
    //    `<file>` paths resolve against $OUT_DIR/ui/*.ui.
    let manifest_src = manifest_dir.join("data/resources.gresource.xml");
    let manifest_out = out_dir.join("resources.gresource.xml");
    std::fs::copy(&manifest_src, &manifest_out).expect("copy gresource manifest");
    println!("cargo:rerun-if-changed={}", manifest_src.display());

    // 3. Bundle into a single .gresource blob.
    let blob = out_dir.join("resources.gresource");
    run(
        Command::new("glib-compile-resources")
            .arg("--target")
            .arg(&blob)
            .arg("--sourcedir")
            .arg(&out_dir)
            .arg(&manifest_out),
        "glib-compile-resources",
    );

    // 4. Rerun if any .blp file changes.
    println!("cargo:rerun-if-changed=data/ui");
}

fn run(cmd: &mut Command, label: &str) {
    let status = cmd.status().unwrap_or_else(|e| {
        panic!(
            "{label} not found (have you installed `blueprint-compiler` and `glib2-devel`?): {e}"
        )
    });
    if !status.success() {
        panic!("{label} failed (exit {status})");
    }
}

#[allow(dead_code)]
fn assert_exists(p: &Path) {
    if !p.exists() {
        panic!("expected {p:?} to exist");
    }
}
