use std::path::Path;

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

pub struct TurborepoPlugin;

impl Plugin for TurborepoPlugin {
    fn name(&self) -> &str {
        "turborepo"
    }

    fn description(&self) -> &str {
        "Turborepo local and global cache"
    }

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

        if dir.join("turbo.json").exists() {
            let turbo_cache = dir.join(".turbo");
            if turbo_cache.is_dir() {
                let size = utils::dir_size(&turbo_cache);
                targets.push(CleanTarget {
                    label: format!("{}", turbo_cache.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(turbo_cache),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Turborepo local build cache".to_string(),
                });
            }

            let next_cache = dir.join("node_modules/.cache/turbo");
            if next_cache.is_dir() {
                let size = utils::dir_size(&next_cache);
                targets.push(CleanTarget {
                    label: format!("{}", next_cache.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(next_cache),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Turborepo build cache in node_modules".to_string(),
                });
            }
        }

        targets
    }

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

        #[cfg(target_os = "macos")]
        let global_cache = home.join("Library/Caches/turbo");
        #[cfg(not(target_os = "macos"))]
        let global_cache = home.join(".cache/turbo");

        if global_cache.is_dir() {
            let size = utils::dir_size(&global_cache);
            targets.push(CleanTarget {
                label: format!("{}", global_cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(global_cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Turborepo global build cache, regenerated on next build".to_string(),
            });
        }

        targets
    }

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

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