//! `kegani clean` command - Clean build artifacts

use anyhow::Result;
use console::{style, Emoji};

/// Clean build artifacts
pub fn clean(all: bool) -> Result<()> {
    println!();
    println!("{}", style("🧹 Cleaning build artifacts").bold());

    if all {
        println!("  {} Removing all build artifacts and cache", style("⚠️").yellow());
    } else {
        println!("  {} Removing target directory", style("•").dim());
    }
    println!();

    // Remove target directory
    let target_path = std::path::Path::new("target");

    if target_path.exists() {
        remove_dir_all::remove_dir_all(target_path)
            .map_err(|e| anyhow::anyhow!("Failed to remove target directory: {}", e))?;
        println!(
            "{} {} removed target directory",
            Emoji("✅", ""),
            style("✓").green()
        );
    }

    // Optionally remove other cache directories
    if all {
        // .cargo-cache
        let cargo_cache = std::path::Path::new(".cargo-cache");
        if cargo_cache.exists() {
            remove_dir_all::remove_dir_all(cargo_cache)
                .map_err(|e| anyhow::anyhow!("Failed to remove .cargo-cache: {}", e))?;
        }

        // .rustup
        let rustup_cache = std::path::Path::new(".rustup-cache");
        if rustup_cache.exists() {
            remove_dir_all::remove_dir_all(rustup_cache)
                .map_err(|e| anyhow::anyhow!("Failed to remove .rustup-cache: {}", e))?;
        }

        println!(
            "{} {} removed additional cache directories",
            Emoji("✅", ""),
            style("✓").green()
        );
    }

    println!();
    println!("{} {}", Emoji("✨", ""), style("Clean completed!").green());
    println!();

    Ok(())
}