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

pub fn handle(outdated: bool) -> anyhow::Result<()> {
    if outdated {
        bail!("`--outdated` not yet implemented");
    }

    let repositories_dir = paths::repositories_dir()?;
    if !repositories_dir.exists() {
        return Ok(());
    }

    let mut packages: Vec<String> = Vec::new();
    for entry in std::fs::read_dir(&repositories_dir)
        .with_context(|| format!("reading {}", repositories_dir.display()))?
    {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let repo = entry.file_name().to_string_lossy().into_owned();
        if Recipe::find(&repo).is_ok() {
            packages.push(repo);
        }
    }

    packages.sort();

    for repo in packages {
        println!("{repo}");
    }

    Ok(())
}
