use std::path::Path;

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

pub struct GradlePlugin;

impl Plugin for GradlePlugin {
    fn name(&self) -> &str {
        "gradle"
    }

    fn description(&self) -> &str {
        "Gradle build outputs and caches"
    }

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

        let has_gradle = dir.join("build.gradle").exists() || dir.join("build.gradle.kts").exists();

        if has_gradle {
            let build_dir = dir.join("build");
            if build_dir.is_dir() {
                let size = utils::dir_size(&build_dir);
                targets.push(CleanTarget {
                    label: format!("{}", build_dir.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(build_dir),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Gradle build output, recreate with `gradle build`".to_string(),
                });
            }
        }

        targets
    }

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

    fn markers(&self) -> &'static [&'static str] {
        &["build.gradle", "build.gradle.kts"]
    }

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

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

        targets
    }
}
