use std::path::Path;

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

pub struct FirefoxPlugin;

impl Plugin for FirefoxPlugin {
    fn name(&self) -> &str {
        "firefox"
    }

    fn description(&self) -> &str {
        "Firefox caches and profile data"
    }

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

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

        // Firefox cache directory (shared across profiles)
        let cache_dir = firefox_cache_dir();
        if cache_dir.is_dir() {
            let size = utils::dir_size(&cache_dir);
            targets.push(CleanTarget {
                label: format!("{}", cache_dir.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(cache_dir),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Browser cache, regenerated automatically".to_string(),
            });
        }

        // Per-profile caches inside the profiles directory
        let profiles_dir = firefox_profiles_dir();
        if profiles_dir.is_dir() {
            if let Ok(entries) = std::fs::read_dir(&profiles_dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let profile = entry.path();
                    if !profile.is_dir() {
                        continue;
                    }

                    // cache2 - main HTTP cache
                    let cache2 = profile.join("cache2");
                    if cache2.is_dir() {
                        let size = utils::dir_size(&cache2);
                        targets.push(CleanTarget {
                            label: format!("{}", cache2.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(cache2),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Recoverable,
                            explanation: "Browser profile cache, regenerated automatically"
                                .to_string(),
                        });
                    }

                    // startupCache - compiled JS and XUL cache
                    let startup_cache = profile.join("startupCache");
                    if startup_cache.is_dir() {
                        let size = utils::dir_size(&startup_cache);
                        targets.push(CleanTarget {
                            label: format!("{}", startup_cache.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(startup_cache),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Recoverable,
                            explanation: "Browser startup cache, regenerated automatically"
                                .to_string(),
                        });
                    }

                    // shader cache
                    let shader_cache = profile.join("shader-cache");
                    if shader_cache.is_dir() {
                        let size = utils::dir_size(&shader_cache);
                        targets.push(CleanTarget {
                            label: format!("{}", shader_cache.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(shader_cache),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Recoverable,
                            explanation: "GPU shader cache, regenerated automatically".to_string(),
                        });
                    }

                    // thumbnails
                    let thumbnails = profile.join("thumbnails");
                    if thumbnails.is_dir() {
                        let size = utils::dir_size(&thumbnails);
                        targets.push(CleanTarget {
                            label: format!("{}", thumbnails.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(thumbnails),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Recoverable,
                            explanation: "Tab thumbnail cache, regenerated automatically"
                                .to_string(),
                        });
                    }

                    // crash reports
                    let crash_reports = profile.join("minidumps");
                    if crash_reports.is_dir() {
                        let size = utils::dir_size(&crash_reports);
                        targets.push(CleanTarget {
                            label: format!("{}", crash_reports.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(crash_reports),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Recoverable,
                            explanation: "Crash dump files".to_string(),
                        });
                    }

                    // storage (Service Workers, IndexedDB, etc.)
                    let storage = profile.join("storage/default");
                    if storage.is_dir() {
                        let size = utils::dir_size(&storage);
                        targets.push(CleanTarget {
                            label: format!("{}", storage.display()),
                            size_bytes: size,
                            action: CleanAction::DeletePath(storage),
                            plugin_name: self.name().to_string(),
                            safety: Safety::Unsafe,
                            explanation: "Firefox site storage data".to_string(),
                        });
                    }
                }
            }
        }

        // Firefox crash reports (global)
        let crash_reports = firefox_crash_reports_dir();
        if crash_reports.is_dir() {
            let size = utils::dir_size(&crash_reports);
            targets.push(CleanTarget {
                label: format!("{}", crash_reports.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(crash_reports),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Crash report data".to_string(),
            });
        }

        targets
    }

    fn is_available(&self) -> bool {
        firefox_profiles_dir().is_dir() || firefox_cache_dir().is_dir()
    }
}

fn firefox_profiles_dir() -> std::path::PathBuf {
    if cfg!(target_os = "macos") {
        utils::home_dir().join("Library/Application Support/Firefox/Profiles")
    } else if cfg!(target_os = "linux") {
        utils::home_dir().join(".mozilla/firefox")
    } else {
        utils::home_dir().join("AppData/Roaming/Mozilla/Firefox/Profiles")
    }
}

fn firefox_cache_dir() -> std::path::PathBuf {
    if cfg!(target_os = "macos") {
        utils::home_dir().join("Library/Caches/Firefox/Profiles")
    } else if cfg!(target_os = "linux") {
        utils::home_dir().join(".cache/mozilla/firefox")
    } else {
        utils::home_dir().join("AppData/Local/Mozilla/Firefox/Profiles")
    }
}

fn firefox_crash_reports_dir() -> std::path::PathBuf {
    if cfg!(target_os = "macos") {
        utils::home_dir().join("Library/Application Support/Firefox/Crash Reports")
    } else if cfg!(target_os = "linux") {
        utils::home_dir().join(".mozilla/firefox/Crash Reports")
    } else {
        utils::home_dir().join("AppData/Roaming/Mozilla/Firefox/Crash Reports")
    }
}
