use std::{
    env,
    path::{Path, PathBuf},
    process::{Command, ExitCode},
};

fn main() -> ExitCode {
    let workspace = workspace_root();
    let rustelo = workspace.parent().unwrap().join("rustelo");
    let nickel_import_path = format!(
        "{}:{}",
        rustelo.join("resources/nickel").display(),
        workspace.join("site/config").display(),
    );

    let mut args = env::args().skip(1).peekable();
    let task = args.next();
    let release = !args.any(|a| a == "--debug");

    let mut cmd = Command::new("cargo");
    cmd.arg("leptos").arg("build");

    match task.as_deref() {
        Some("wasm") | Some("frontend") => { cmd.arg("--frontend-only"); }
        Some("server") => { cmd.arg("--server-only"); }
        None | Some("all") | Some("build") => {}
        Some(unknown) => {
            eprintln!("unknown task: {unknown}");
            eprintln!("usage: cargo xtask [wasm|server|all] [--debug]");
            return ExitCode::FAILURE;
        }
    }

    if release {
        cmd.arg("--release");
    }

    let status = cmd
        .env("NICKEL_IMPORT_PATH", &nickel_import_path)
        .current_dir(&workspace)
        .status()
        .expect("cargo not found — is it in PATH?");

    if status.success() { ExitCode::SUCCESS } else { ExitCode::FAILURE }
}

fn workspace_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("xtask must be a direct child of the workspace root")
        .to_path_buf()
}
