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

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

    let repo_path = paths::repositories_dir()?.join(repo);
    let recipe_path = paths::recipes_dir()?.join(format!("{repo}.toml"));

    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);

    let commit = if repo_path.exists() {
        git::head_commit(&repo_path).unwrap_or_else(|_| String::from("(unknown)"))
    } else {
        String::from("(not cloned)")
    };

    println!("{repo}");
    println!("  github       {}", recipe.package.slug());
    if let Some(desc) = &recipe.package.description {
        println!("  description  {desc}");
    }
    println!("  commit       {commit}");
    println!("  repo         {}", repo_path.display());
    println!("  recipe       {}", recipe_path.display());
    println!("  binary       {}", binary_path.display());

    Ok(())
}
