use anyhow::{Context, anyhow};
use dolly_cli::{git, paths, ui};

pub fn handle(name: &str) -> anyhow::Result<()> {
    let (_owner, repo) = name
        .split_once('/')
        .filter(|(o, n)| !o.is_empty() && !n.is_empty() && !n.contains('/'))
        .ok_or_else(|| anyhow!("repo must be in `owner/repo` form"))?;

    let repositories_dir = paths::repositories_dir()?;
    std::fs::create_dir_all(&repositories_dir)
        .with_context(|| format!("creating {}", repositories_dir.display()))?;

    let url = format!("https://github.com/{name}.git");
    let dest = repositories_dir.join(repo);

    ui::status("Cloning", name);
    git::clone(&url, &dest).with_context(|| format!("cloning `{name}`"))?;
    Ok(())
}
