use std::process::Command;
use vergen::EmitBuilder;

fn try_cmd(cmd: &mut Command) -> Option<String> {
    let out = cmd.output().ok()?;
    if !out.status.success() {
        return None;
    }
    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn main() {
    // Emit all default vergen build info (BUILD_DATE / BUILD_TIME, etc.)
    EmitBuilder::builder().all_build();

    // Git describe + commit date (matches your Python logic)
    let commit_info = (|| {
        let hash = try_cmd(
            Command::new("git")
                .arg("describe")
                .arg("--always")
                .arg("--dirty")
                .arg("--abbrev=7"),
        )?;

        let date = try_cmd(
            Command::new("git")
                .arg("show")
                .arg("-s")
                .arg("--format=%ci"),
        )?;

        Some(format!("{} {}", hash, date))
    })()
    .unwrap_or_else(|| "unknown".into());

    println!("cargo:rustc-env=GIT_COMMIT_HASH={}", commit_info);

    // Compiler info
    println!("cargo:rustc-env=COMPILER_NAME=rustc");

    let rustc_ver = try_cmd(Command::new("rustc").arg("--version"))
        .unwrap_or_else(|| "unknown".into());
    println!("cargo:rustc-env=COMPILER_VER={}", rustc_ver);
}
