use std::path::Path;

use crate::plugin::{CleanAction, CleanTarget, Plugin, Safety};
use crate::utils;

pub struct CargoPlugin;

impl Plugin for CargoPlugin {
    fn name(&self) -> &str {
        "cargo"
    }

    fn description(&self) -> &str {
        "Rust/Cargo build artifacts and registry cache"
    }

    fn scan_directory(&self, dir: &Path) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        let cargo_toml = dir.join("Cargo.toml");
        if cargo_toml.exists() {
            let target_dir = dir.join("target");
            if target_dir.is_dir() {
                let size = utils::dir_size(&target_dir);
                targets.push(CleanTarget {
                    label: format!("{}", target_dir.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(target_dir),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Rust build artifacts, recreate with `cargo build`".to_string(),
                });
            }
        }

        targets
    }

    fn global_targets(&self) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        let registry_cache = utils::home_dir().join(".cargo/registry/cache");
        if registry_cache.is_dir() {
            let size = utils::dir_size(&registry_cache);
            targets.push(CleanTarget {
                label: format!("{}", registry_cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(registry_cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Cargo registry cache, re-downloaded as needed".to_string(),
            });
        }

        targets
    }

    fn skip_subdirectories(&self) -> &'static [&'static str] {
        &["target"]
    }

    fn markers(&self) -> &'static [&'static str] {
        &["Cargo.toml"]
    }
}
