use std::path::Path;

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

pub struct NodePlugin;

impl Plugin for NodePlugin {
    fn name(&self) -> &str {
        "node"
    }

    fn description(&self) -> &str {
        "Node.js node_modules and npm cache"
    }

    fn scan_directory(&self, dir: &Path) -> Vec<CleanTarget> {
        // Skip node_modules inside application bundles
        if is_inside_app_bundle(dir) {
            return Vec::new();
        }

        let mut targets = Vec::new();

        let package_json = dir.join("package.json");
        if package_json.exists() {
            let node_modules = dir.join("node_modules");
            if node_modules.is_dir() {
                let size = utils::dir_size(&node_modules);
                targets.push(CleanTarget {
                    label: format!("{}", node_modules.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(node_modules),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "npm dependencies, reinstall with `npm install`".to_string(),
                });
            }
        }

        targets
    }

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

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

        targets
    }

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

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

/// Check if a path is inside a .app, .framework, or similar macOS/Linux
/// application bundle that should not be tampered with.
fn is_inside_app_bundle(path: &Path) -> bool {
    for ancestor in path.ancestors() {
        if let Some(name) = ancestor.file_name() {
            let name = name.to_string_lossy();
            if name.ends_with(".app")
                || name.ends_with(".framework")
                || name == "Applications"
                || name == "Application Support"
            {
                return true;
            }
        }
    }
    false
}
