use std::path::Path;

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

pub struct AndroidPlugin;

impl Plugin for AndroidPlugin {
    fn name(&self) -> &str {
        "android"
    }

    fn description(&self) -> &str {
        "Android SDK caches, emulators, and build artifacts"
    }

    fn is_available(&self) -> bool {
        let home = utils::home_dir();
        let sdk = android_sdk_dir();
        sdk.is_dir() || home.join(".android").is_dir()
    }

    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();
        let sdk = android_sdk_dir();

        // AVD (emulator) images — can be very large
        let avd = home.join(".android/avd");
        if avd.is_dir() {
            let size = utils::dir_size(&avd);
            targets.push(CleanTarget {
                label: format!("{}", avd.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(avd),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "Android emulator disk images".to_string(),
            });
        }

        // Android cache (debug keys, analytics, etc.)
        let android_cache = home.join(".android/cache");
        if android_cache.is_dir() {
            let size = utils::dir_size(&android_cache);
            targets.push(CleanTarget {
                label: format!("{}", android_cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(android_cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Android SDK cache, re-downloaded as needed".to_string(),
            });
        }

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

        // System images (downloaded for emulators)
        let system_images = sdk.join("system-images");
        if system_images.is_dir() {
            let size = utils::dir_size(&system_images);
            targets.push(CleanTarget {
                label: format!("{}", system_images.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(system_images),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "Android emulator system images, re-downloadable via SDK Manager"
                    .to_string(),
            });
        }

        // .downloadIntermediates (partial SDK downloads)
        let intermediates = sdk.join(".downloadIntermediates");
        if intermediates.is_dir() {
            let size = utils::dir_size(&intermediates);
            targets.push(CleanTarget {
                label: format!("{}", intermediates.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(intermediates),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Android SDK download intermediates".to_string(),
            });
        }

        // NDK (multiple versions can pile up)
        let ndk = sdk.join("ndk");
        if ndk.is_dir() {
            let size = utils::dir_size(&ndk);
            targets.push(CleanTarget {
                label: format!("{}", ndk.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(ndk),
                plugin_name: self.name().to_string(),
                safety: Safety::Unsafe,
                explanation: "Android NDK, re-downloadable via SDK Manager".to_string(),
            });
        }

        targets
    }
}

/// Return the Android SDK directory, respecting ANDROID_HOME / ANDROID_SDK_ROOT.
fn android_sdk_dir() -> std::path::PathBuf {
    if let Ok(v) = std::env::var("ANDROID_HOME") {
        return std::path::PathBuf::from(v);
    }
    if let Ok(v) = std::env::var("ANDROID_SDK_ROOT") {
        return std::path::PathBuf::from(v);
    }
    let home = utils::home_dir();
    #[cfg(target_os = "macos")]
    {
        home.join("Library/Android/sdk")
    }
    #[cfg(target_os = "linux")]
    {
        home.join("Android/Sdk")
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        home.join("Android/Sdk")
    }
}
