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

fn main() {
    let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
    let frontend_dir = Path::new(&manifest_dir).join("frontend");

    println!("cargo:rerun-if-changed=frontend/src");
    println!("cargo:rerun-if-changed=frontend/package.json");
    println!("cargo:rerun-if-changed=frontend/next.config.ts");

    // Always clean-install so platform-specific native deps (e.g. @tailwindcss/oxide)
    // are correct for the build host, not whatever platform wrote the lock file.
    let nm = frontend_dir.join("node_modules");
    if nm.exists() {
        std::fs::remove_dir_all(&nm).expect("Failed to remove frontend/node_modules");
    }
    let status = Command::new("npm")
        .arg("install")
        .arg("--force")
        .current_dir(&frontend_dir)
        .status()
        .expect("Failed to run npm install. Is Node.js installed?");
    assert!(status.success(), "npm install failed");

    let status = Command::new("npm")
        .args(["run", "build"])
        .current_dir(&frontend_dir)
        .status()
        .expect("Failed to run npm run build");
    assert!(status.success(), "npm run build failed");
}
