Skip to content
use std::fs;
use std::path::Path;

pub fn set_mode(mode: &str) -> Result<(), Box<dyn std::error::Error>> {
    match mode {
        "alpha" | "beta" | "normal" => {}
        _ => {
            eprintln!(
                "Error: Invalid mode '{}'. Use 'alpha', 'beta', or 'normal'",
                mode
            );
            std::process::exit(1);
        }
    }

    if !Path::new("Cargo.toml").exists() {
        eprintln!("Error: No Cargo.toml found in current directory.");
        std::process::exit(1);
    }

    let cargo_content = fs::read_to_string("Cargo.toml")?;
    let mut cargo_toml: toml::Value = cargo_content.parse()?;

    if let Some(spruce) = cargo_toml.get_mut("spruce") {
        if let toml::Value::Table(table) = spruce {
            table.insert("mode".to_string(), toml::Value::String(mode.to_string()));
        }
    } else {
        eprintln!("Error: No [spruce] section found. Please run 'spruce init' first.");
        std::process::exit(1);
    }

    let updated_cargo = toml::to_string_pretty(&cargo_toml)?;
    fs::write("Cargo.toml", updated_cargo)?;

    println!("[OK] Set mode to '{}' in Cargo.toml [spruce] section", mode);
    match mode {
        "alpha" => println!("  Next build will bump patch version (e.g., 0.1.0 -> 0.1.1)"),
        "beta" => println!("  Next build will bump minor version (e.g., 0.1.3 -> 0.2.0)"),
        "normal" => println!("  Next build will bump patch version (e.g., 0.1.0 -> 0.1.1)"),
        _ => {}
    }

    Ok(())
}