use std::{
    io::{self, Write},
    path::Path,
    process,
};

fn main() {
    println!("cargo::rustc-check-cfg=cfg(web_sys_unstable_apis)");
    println!("cargo:rerun-if-changed=uno.config.ts");
    //println!("cargo:rerun-if-changed=style/main.scss");

    // Check if node_modules exists in various locations, if not run pnpm install
    let node_modules_paths = ["../node_modules", "node_modules", "../../node_modules"];

    let node_modules_exists = node_modules_paths
        .iter()
        .any(|path| Path::new(path).exists());

    if !node_modules_exists {
        println!("cargo:warning=node_modules not found, running pnpm install...");

        // Try to find package.json to determine correct directory
        let package_json_paths = ["../package.json", "package.json", "../../package.json"];

        let install_dir = package_json_paths
            .iter()
            .find(|path| Path::new(path).exists())
            .map(|path| Path::new(path).parent().unwrap_or(Path::new(".")))
            .unwrap_or(Path::new(".."));

        match process::Command::new("pnpm")
            .arg("install")
            .current_dir(install_dir)
            .output()
        {
            Ok(output) => {
                if !output.status.success() {
                    let _ = io::stdout().write_all(&output.stdout);
                    let _ = io::stdout().write_all(&output.stderr);
                    panic!("pnpm install failed");
                }
                println!("cargo:warning=pnpm install completed successfully");
            }
            Err(e) => {
                println!("cargo:warning=Failed to run pnpm install: {:?}", e);
                println!("cargo:warning=Please run 'pnpm install' manually in the project root");
                // Don't panic here, just warn - the build might still work
            }
        }
    }

    match process::Command::new("sh")
        .arg("-c")
        .arg("pnpm run build")
        .output()
    {
        Ok(output) => {
            if !output.status.success() {
                let _ = io::stdout().write_all(&output.stdout);
                let _ = io::stdout().write_all(&output.stderr);
                panic!("UnoCSS error");
            }
        }
        Err(e) => panic!("UnoCSS error: {:?}", e),
    };
}
