use std::path::Path;

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

pub struct BazelPlugin;

impl Plugin for BazelPlugin {
    fn name(&self) -> &str {
        "bazel"
    }

    fn description(&self) -> &str {
        "Bazel build outputs and cache"
    }

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

        let has_workspace = dir.join("WORKSPACE").exists()
            || dir.join("WORKSPACE.bazel").exists()
            || dir.join("MODULE.bazel").exists();

        if has_workspace {
            for name in ["bazel-bin", "bazel-out", "bazel-testlogs"] {
                let path = dir.join(name);
                if path.exists() {
                    let size = utils::dir_size(&path);
                    targets.push(CleanTarget {
                        label: format!("{}", path.display()),
                        size_bytes: size,
                        action: CleanAction::DeletePath(path),
                        plugin_name: self.name().to_string(),
                        safety: Safety::Recoverable,
                        explanation: "Bazel build output, regenerated with `bazel build`"
                            .to_string(),
                    });
                }
            }
        }

        targets
    }

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

        let cache = utils::home_dir().join(".cache").join("bazel");
        if cache.is_dir() {
            let size = utils::dir_size(&cache);
            targets.push(CleanTarget {
                label: format!("{}", cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Bazel global cache, regenerated as needed".to_string(),
            });
        }

        targets
    }

    fn markers(&self) -> &'static [&'static str] {
        &["WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel"]
    }
}
