use std::env;
use std::path::Path;
use std::process::Command;

fn run(cmd: &str, args: &[&str], dir: &Path) {
    let status = Command::new(cmd)
        .args(args)
        .current_dir(dir)
        .status()
        .unwrap_or_else(|e| panic!("Failed to run {} {:?}: {}", cmd, args, e));

    if !status.success() {
        panic!("Command failed: {} {:?}", cmd, args);
    }
}

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-env-changed=PROFILE");

    // Embed the current git commit hash at compile time so `get_version` always
    // reflects the binary that is actually running, not a potentially-stale file.
    println!("cargo:rerun-if-changed=../.git/HEAD");
    println!("cargo:rerun-if-changed=../.git/refs/");
    let git_hash = std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".to_string());
    println!("cargo:rustc-env=BUILD_GIT_HASH={git_hash}");
    println!("cargo:rerun-if-changed=../frontend/package.json");
    println!("cargo:rerun-if-changed=../frontend/package-lock.json");
    println!("cargo:rerun-if-changed=../frontend/vite.config.ts");
    println!("cargo:rerun-if-changed=../frontend/index.html");
    println!("cargo:rerun-if-changed=../frontend/src");
    println!("cargo:rerun-if-changed=../frontend/public");

    let profile = env::var("PROFILE").unwrap_or_default();
    if profile != "release" {
        return;
    }

    // When cross-compiling (e.g. musl via `cross`), the Docker container
    // has no Node/npm. The release script builds macOS first, so
    // frontend/dist/ already exists. Skip the frontend build in that case.
    let target = env::var("TARGET").unwrap_or_default();
    let host = env::var("HOST").unwrap_or_default();
    if target != host {
        let dist = Path::new("../frontend/dist");
        if !dist.exists() {
            panic!("Cross-compiling but frontend/dist/ is missing. Build macOS first.");
        }
        return;
    }

    let frontend_dir = Path::new("../frontend");

    // Ensure dependencies are installed and build the frontend bundle.
    run("npm", &["install"], frontend_dir);
    run("npm", &["run", "build"], frontend_dir);
}
