//! Emits the M3-frozen kernel staticlib and links it.
//!
//! Resolution of the `ail` binary has no in-repo precedent (the
//! in-test mechanism `env!("CARGO_BIN_EXE_ail")` is unavailable to a
//! workspace-excluded crate's build script): use `$AIL_BIN` if set,
//! else `cargo build --manifest-path <repo>/Cargo.toml -p ail` and
//! use `<repo>/target/debug/ail`. The AILang workspace target dir
//! (`<repo>/target`) is distinct from this crate's
//! (`ail-embed/target`), so the nested `cargo build` cannot deadlock
//! on the outer build's lock.
use std::env;
use std::path::PathBuf;
use std::process::Command;

fn main() {
    let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let repo = manifest.parent().unwrap().to_path_buf(); // /home/brummel/dev/ailang
    let kernel = repo.join("examples/embed_backtest_step_tick.ail");
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());

    println!("cargo:rerun-if-changed={}", kernel.display());
    println!("cargo:rerun-if-changed=build.rs");
    // `ail build --emit=staticlib` compiles libailang_rt.a from the
    // runtime C sources (rc.c + str.c — see crates/ail build_staticlib).
    // Track the whole `runtime/` directory (Cargo recurses mtimes
    // under a directory path) so any runtime change relinks the
    // archive. A per-file list would silently re-introduce staleness
    // for any future runtime source; the directory mechanism cannot.
    println!("cargo:rerun-if-changed={}", repo.join("runtime").display());
    println!("cargo:rerun-if-env-changed=AIL_BIN");

    let ail_bin: PathBuf = match env::var("AIL_BIN") {
        Ok(p) => PathBuf::from(p),
        Err(_) => {
            let status = Command::new("cargo")
                .args(["build", "--manifest-path"])
                .arg(repo.join("Cargo.toml"))
                .args(["-p", "ail"])
                .status()
                .expect("spawn `cargo build -p ail`");
            assert!(status.success(), "building the `ail` CLI failed");
            repo.join("target/debug/ail")
        }
    };

    let build = Command::new(&ail_bin)
        .arg("build")
        .arg(&kernel)
        .args(["--emit=staticlib", "-o"])
        .arg(&out_dir)
        .output()
        .expect("spawn `ail build --emit=staticlib`");
    assert!(
        build.status.success(),
        "ail build --emit=staticlib failed:\n{}",
        String::from_utf8_lossy(&build.stderr)
    );

    println!("cargo:rustc-link-search=native={}", out_dir.display());
    println!("cargo:rustc-link-lib=static=embed_backtest_step_tick");
    println!("cargo:rustc-link-lib=static=ailang_rt");
}
