use std::path::Path;

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

pub struct OrbstackPlugin;

impl Plugin for OrbstackPlugin {
    fn name(&self) -> &str {
        "orbstack"
    }

    fn description(&self) -> &str {
        "OrbStack VM data, logs, and caches"
    }

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

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

        // Logs
        let log_dir = home.join(".orbstack/log");
        if log_dir.is_dir() {
            let size = utils::dir_size(&log_dir);
            targets.push(CleanTarget {
                label: format!("{}", log_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(log_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "OrbStack log files".to_string(),
            });
        }

        // Sentry crash reports
        let crash_dir = home.join("Library/Caches/SentryCrash/OrbStack");
        if crash_dir.is_dir() {
            let size = utils::dir_size(&crash_dir);
            targets.push(CleanTarget {
                label: format!("{}", crash_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(crash_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "OrbStack crash reports".to_string(),
            });
        }

        // VM disk image (data.img.raw) — the big one
        let data_dir = home.join("Library/Group Containers/HUAQ24HBR6.dev.orbstack/data");
        let disk_image = data_dir.join("data.img.raw");
        if disk_image.is_file() {
            // Use actual on-disk size (sparse file), not logical size
            let size = disk_image
                .metadata()
                .map(|m| {
                    use std::os::unix::fs::MetadataExt;
                    m.blocks() * 512
                })
                .unwrap_or(0);
            targets.push(CleanTarget {
                label: format!("{}", disk_image.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(data_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "OrbStack VM disk image".to_string(),
            });
        }

        targets
    }

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