use std::path::Path;

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

pub struct DownloadsPlugin;

impl Plugin for DownloadsPlugin {
    fn name(&self) -> &str {
        "downloads"
    }

    fn description(&self) -> &str {
        "Downloads folder contents"
    }

    fn scan_directory(&self, _dir: &Path) -> Vec<CleanTarget> {
        Vec::new()
    }

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

        let downloads = utils::home_dir().join("Downloads");
        if !downloads.is_dir() {
            return targets;
        }

        let entries = match std::fs::read_dir(&downloads) {
            Ok(e) => e,
            Err(_) => return targets,
        };

        for entry in entries.flatten() {
            let path = entry.path();

            // Skip hidden files (e.g. .DS_Store, .localized)
            if entry.file_name().to_string_lossy().starts_with('.') {
                continue;
            }

            let size = if path.is_dir() {
                utils::dir_size(&path)
            } else {
                path.metadata()
                    .map(|m| utils::physical_size(&m))
                    .unwrap_or(0)
            };

            if size == 0 {
                continue;
            }

            targets.push(CleanTarget {
                label: format!("{}", path.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(path),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: String::new(),
            });
        }

        targets
    }

    fn is_available(&self) -> bool {
        utils::home_dir().join("Downloads").is_dir()
    }
}
