package party.cybsec.griefdetect.config;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import party.cybsec.griefdetect.GriefDetectPlugin;

import java.io.File;
import java.io.IOException;

/**
 * Configuration manager for GriefDetect plugin.
 * Handles loading, saving, and accessing all plugin configuration.
 */
public class PluginConfig {
    
    private final GriefDetectPlugin plugin;
    private FileConfiguration config;
    private File configFile;
    
    // Configuration keys
    private static final String GLOBAL_ENABLE = "global.enable";
    private static final String GLOBAL_ASYNC = "global.async";
    
    private static final String PERMISSIONS_ADMIN = "permissions.admin";
    private static final String PERMISSIONS_RELOAD = "permissions.reload";
    private static final String PERMISSIONS_ALERTS = "permissions.alerts";
    private static final String PERMISSIONS_BYPASS = "permissions.bypass";
    
    private static final String WEBHOOK_ENABLED = "webhook.enabled";
    private static final String WEBHOOK_URL = "webhook.url";
    private static final String WEBHOOK_THRESHOLD = "webhook.threshold";
    private static final String WEBHOOK_RETRY_ATTEMPTS = "webhook.retryAttempts";
    private static final String WEBHOOK_RETRY_DELAY = "webhook.retryDelay";
    private static final String WEBHOOK_COOLDOWN = "webhook.areaCooldown";
    
    private static final String CHAT_ENABLED = "chat.enabled";
    private static final String CHAT_THRESHOLD = "chat.threshold";
    private static final String CHAT_FORMAT = "chat.format";
    
    private static final String ENGINE_INTERVAL = "engine.analysisInterval";
    private static final String ENGINE_TIMEOUT = "engine.clusterTimeout";
    private static final String ENGINE_MAX_CLUSTERS = "engine.maxClustersPerWorld";
    
    private static final String MODULES_PREFIX = "modules.";
    
    // Default values
    private static final boolean DEFAULT_GLOBAL_ENABLE = true;
    private static final boolean DEFAULT_GLOBAL_ASYNC = true;
    
    private static final String DEFAULT_PERMISSIONS_ADMIN = "griefdetect.admin";
    private static final String DEFAULT_PERMISSIONS_RELOAD = "griefdetect.reload";
    private static final String DEFAULT_PERMISSIONS_ALERTS = "griefdetect.alerts";
    private static final String DEFAULT_PERMISSIONS_BYPASS = "griefdetect.bypass";
    
    private static final boolean DEFAULT_WEBHOOK_ENABLED = false;
    private static final String DEFAULT_WEBHOOK_URL = "";
    private static final double DEFAULT_WEBHOOK_THRESHOLD = 75.0;
    private static final int DEFAULT_WEBHOOK_RETRY_ATTEMPTS = 3;
    private static final int DEFAULT_WEBHOOK_RETRY_DELAY = 5000;
    private static final int DEFAULT_WEBHOOK_COOLDOWN = 300;
    
    private static final boolean DEFAULT_CHAT_ENABLED = true;
    private static final double DEFAULT_CHAT_THRESHOLD = 50.0;
    private static final String DEFAULT_CHAT_FORMAT = "&c[GriefDetect] &7%s &fat &6%s:%d,%d,%d &7(%d%%)";
    
    private static final int DEFAULT_ENGINE_INTERVAL = 5000;
    private static final int DEFAULT_ENGINE_TIMEOUT = 300000; // 5 minutes
    private static final int DEFAULT_ENGINE_MAX_CLUSTERS = 50;
    
    public PluginConfig(GriefDetectPlugin plugin) {
        this.plugin = plugin;
        this.configFile = new File(plugin.getDataFolder(), "config.yml");
    }
    
    /**
     * Load the configuration file.
     */
    public void load() {
        // Create data folder if it doesn't exist
        if (!plugin.getDataFolder().exists()) {
            plugin.getDataFolder().mkdirs();
        }
        
        // Create default config if it doesn't exist
        if (!configFile.exists()) {
            plugin.saveResource("config.yml", false);
        }
        
        // Load configuration
        config = YamlConfiguration.loadConfiguration(configFile);
        setDefaults();
        
        try {
            config.save(configFile);
        } catch (IOException e) {
            plugin.getLogger().severe("Could not save config to " + configFile);
        }
    }
    
    /**
     * Set default configuration values.
     */
    private void setDefaults() {
        // Global settings
        config.addDefault(GLOBAL_ENABLE, DEFAULT_GLOBAL_ENABLE);
        config.addDefault(GLOBAL_ASYNC, DEFAULT_GLOBAL_ASYNC);
        
        // Permissions
        config.addDefault(PERMISSIONS_ADMIN, DEFAULT_PERMISSIONS_ADMIN);
        config.addDefault(PERMISSIONS_RELOAD, DEFAULT_PERMISSIONS_RELOAD);
        config.addDefault(PERMISSIONS_ALERTS, DEFAULT_PERMISSIONS_ALERTS);
        config.addDefault(PERMISSIONS_BYPASS, DEFAULT_PERMISSIONS_BYPASS);
        
        // Webhook settings
        config.addDefault(WEBHOOK_ENABLED, DEFAULT_WEBHOOK_ENABLED);
        config.addDefault(WEBHOOK_URL, DEFAULT_WEBHOOK_URL);
        config.addDefault(WEBHOOK_THRESHOLD, DEFAULT_WEBHOOK_THRESHOLD);
        config.addDefault(WEBHOOK_RETRY_ATTEMPTS, DEFAULT_WEBHOOK_RETRY_ATTEMPTS);
        config.addDefault(WEBHOOK_RETRY_DELAY, DEFAULT_WEBHOOK_RETRY_DELAY);
        config.addDefault(WEBHOOK_COOLDOWN, DEFAULT_WEBHOOK_COOLDOWN);
        
        // Chat settings
        config.addDefault(CHAT_ENABLED, DEFAULT_CHAT_ENABLED);
        config.addDefault(CHAT_THRESHOLD, DEFAULT_CHAT_THRESHOLD);
        config.addDefault(CHAT_FORMAT, DEFAULT_CHAT_FORMAT);
        
        // Engine settings
        config.addDefault(ENGINE_INTERVAL, DEFAULT_ENGINE_INTERVAL);
        config.addDefault(ENGINE_TIMEOUT, DEFAULT_ENGINE_TIMEOUT);
        config.addDefault(ENGINE_MAX_CLUSTERS, DEFAULT_ENGINE_MAX_CLUSTERS);
        
        // Module defaults
        config.addDefault(MODULES_PREFIX + "LavaCastDetector.enabled", true);
        config.addDefault(MODULES_PREFIX + "LavaCastDetector.minBlockCount", 10);
        config.addDefault(MODULES_PREFIX + "LavaCastDetector.minDuration", 5000);
        config.addDefault(MODULES_PREFIX + "LavaCastDetector.suppressionThreshold", 0.1);
        
        config.options().copyDefaults(true);
    }
    
    /**
     * Reload configuration from file.
     */
    public void reload() {
        config = YamlConfiguration.loadConfiguration(configFile);
        setDefaults();
    }
    
    // Global getters
    public boolean isGlobalEnabled() {
        return config.getBoolean(GLOBAL_ENABLE, DEFAULT_GLOBAL_ENABLE);
    }
    
    public boolean isAsyncEnabled() {
        return config.getBoolean(GLOBAL_ASYNC, DEFAULT_GLOBAL_ASYNC);
    }
    
    // Permission getters
    public String getPermissionAdmin() {
        return config.getString(PERMISSIONS_ADMIN, DEFAULT_PERMISSIONS_ADMIN);
    }
    
    public String getPermissionReload() {
        return config.getString(PERMISSIONS_RELOAD, DEFAULT_PERMISSIONS_RELOAD);
    }
    
    public String getPermissionAlerts() {
        return config.getString(PERMISSIONS_ALERTS, DEFAULT_PERMISSIONS_ALERTS);
    }
    
    public String getPermissionBypass() {
        return config.getString(PERMISSIONS_BYPASS, DEFAULT_PERMISSIONS_BYPASS);
    }
    
    // Webhook getters
    public boolean isWebhookEnabled() {
        return config.getBoolean(WEBHOOK_ENABLED, DEFAULT_WEBHOOK_ENABLED);
    }
    
    public String getWebhookUrl() {
        return config.getString(WEBHOOK_URL, DEFAULT_WEBHOOK_URL);
    }
    
    public double getWebhookThreshold() {
        return config.getDouble(WEBHOOK_THRESHOLD, DEFAULT_WEBHOOK_THRESHOLD);
    }
    
    public int getWebhookRetryAttempts() {
        return config.getInt(WEBHOOK_RETRY_ATTEMPTS, DEFAULT_WEBHOOK_RETRY_ATTEMPTS);
    }
    
    public int getWebhookRetryDelay() {
        return config.getInt(WEBHOOK_RETRY_DELAY, DEFAULT_WEBHOOK_RETRY_DELAY);
    }
    
    public int getWebhookCooldown() {
        return config.getInt(WEBHOOK_COOLDOWN, DEFAULT_WEBHOOK_COOLDOWN);
    }
    
    // Chat getters
    public boolean isChatEnabled() {
        return config.getBoolean(CHAT_ENABLED, DEFAULT_CHAT_ENABLED);
    }
    
    public double getChatAlertThreshold() {
        return config.getDouble(CHAT_THRESHOLD, DEFAULT_CHAT_THRESHOLD);
    }
    
    public double getIgnoreThreshold() {
        return 25.0; // Default ignore threshold
    }
    
    public String getChatFormat() {
        return config.getString(CHAT_FORMAT, DEFAULT_CHAT_FORMAT);
    }
    
    // Engine getters
    public int getEngineAnalysisInterval() {
        return config.getInt(ENGINE_INTERVAL, DEFAULT_ENGINE_INTERVAL);
    }
    
    public int getEngineClusterTimeout() {
        return config.getInt(ENGINE_TIMEOUT, DEFAULT_ENGINE_TIMEOUT);
    }
    
    public int getEngineMaxClustersPerWorld() {
        return config.getInt(ENGINE_MAX_CLUSTERS, DEFAULT_ENGINE_MAX_CLUSTERS);
    }
    
    // Module getters
    public boolean isModuleEnabled(String moduleName) {
        return config.getBoolean(MODULES_PREFIX + moduleName + ".enabled", true);
    }
    
    public int getLavaCastMinBlockCount() {
        return config.getInt(MODULES_PREFIX + "LavaCastDetector.minBlockCount", 10);
    }
    
    public int getLavaCastMinDuration() {
        return config.getInt(MODULES_PREFIX + "LavaCastDetector.minDuration", 5000);
    }
    
    public double getLavaCastSuppressionThreshold() {
        return config.getDouble(MODULES_PREFIX + "LavaCastDetector.suppressionThreshold", 0.1);
    }
    
    /**
     * Get the raw configuration for advanced access.
     */
    public FileConfiguration getConfig() {
        return config;
    }
}