use anyhow::{Context, anyhow};
use dolly_cli::{paths, recipe::Recipe, ui};

pub fn handle(repo: &str, keep_repo: bool) -> anyhow::Result<()> {
    let recipe = Recipe::find(repo).with_context(|| format!("loading recipe for `{repo}`"))?;

    let bin_name = recipe
        .build
        .output
        .file_name()
        .ok_or_else(|| anyhow!("`build.output` has no filename"))?;
    let binary_path = paths::default_install_dir()?.join(bin_name);

    if binary_path.exists() {
        std::fs::remove_file(&binary_path)
            .with_context(|| format!("removing binary at {}", binary_path.display()))?;
    }

    if !keep_repo {
        let repo_path = paths::repositories_dir()?.join(repo);
        if repo_path.exists() {
            std::fs::remove_dir_all(&repo_path)
                .with_context(|| format!("removing repo at {}", repo_path.display()))?;
        }
    }

    ui::status("Removed", repo);
    Ok(())
}
