use std::path::Path;

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

pub struct SwiftPlugin;

impl Plugin for SwiftPlugin {
    fn name(&self) -> &str {
        "swift"
    }

    fn description(&self) -> &str {
        "Swift Package Manager build artifacts and DerivedData"
    }

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

        let package_swift = dir.join("Package.swift");
        if package_swift.exists() {
            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: "Swift build artifacts, recreate with `swift build`".to_string(),
                });
            }
        }

        targets
    }

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

        let derived_data = utils::home_dir().join("Library/Developer/Xcode/DerivedData");
        if derived_data.is_dir() {
            let size = utils::dir_size(&derived_data);
            targets.push(CleanTarget {
                label: format!("{}", derived_data.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(derived_data),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Xcode derived data, regenerated on next build".to_string(),
            });
        }

        targets
    }

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

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