package eu.mrneznamy.mrultimatelibrary.config;

import eu.mrneznamy.mrultimatelibrary.scheduler.MrLibScheduler;
import eu.mrneznamy.mrultimatelibrary.utils.MrLibConsoleSayer;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

/**
 * Legacy remote config downloader. Remote backend is disabled.
 */
public class MrLibConfigDownloader {
    
    private static final String BASE_URL = "";
    private static final int TIMEOUT = 10000; 
    
    private final JavaPlugin plugin;
    private final String pluginName;
    
    public MrLibConfigDownloader(JavaPlugin plugin) {
        this.plugin = plugin;
        this.pluginName = plugin.getName();
    }
    
    /**
     * Downloads all configuration files for the plugin asynchronously
     * This is called automatically on plugin enable
     */
    public void downloadConfigs() {
        MrLibScheduler.runTaskAsynchronously(plugin, this::performDownload);
    }

    /**
     * Downloads all configuration files for the plugin synchronously
     */
    public void downloadConfigsSync() {
        performDownload();
    }

    private void performDownload() {
        return;
        /*
        try {
            
            convertOldConfigs();
            
            
            Map<String, Integer> configVersions = getConfigVersions();
            
            if (configVersions.isEmpty()) {
                MrLibConsoleSayer.MrSay_Warning("No remote configurations found, using defaults");
                
                createDefaultConfigs();
                return;
            }
            
            
            if (pluginName.equals("MrUltimateShop")) {
                downloadMrUltimateShopConfigs(configVersions);
            } else if (pluginName.equals("MrUltimateJobs")) {
                downloadMrUltimateJobsConfigs(configVersions);
            } else {
                
                for (Map.Entry<String, Integer> entry : configVersions.entrySet()) {
                    String configName = entry.getKey();
                    int remoteVersion = entry.getValue();
                    
                    downloadConfig(configName, remoteVersion);
                }
            }
            
            MrLibConsoleSayer.MrSay_Success("Configuration files loaded successfully");
            
            
            
            
            MrLibScheduler.runTask(plugin, () -> {
                if (pluginName.equals("MrUltimateJobs")) {
                    try {
                        
                        java.lang.reflect.Method reload = plugin.getClass().getMethod("reload");
                        reload.invoke(plugin);
                        MrLibConsoleSayer.MrSay_Info("[" + pluginName + "] Triggered internal config reload");
                    } catch (Exception e) {
                        if (plugin.getConfig().getBoolean("Debug.Enabled", false)) {
                            MrLibConsoleSayer.MrSay_Warning("Failed to trigger internal reload: " + e.getMessage());
                        }
                    }
                } else if (pluginName.equals("MrUltimateShop")) {
                    try {
                        
                        java.lang.reflect.Method reloadConfiguration = plugin.getClass().getMethod("reloadConfiguration");
                        reloadConfiguration.invoke(plugin);
                        MrLibConsoleSayer.MrSay_Info("[" + pluginName + "] Triggered internal config reload");
                    } catch (Exception e) {
                        if (plugin.getConfig().getBoolean("Debug.Enabled", false)) {
                            MrLibConsoleSayer.MrSay_Warning("[" + pluginName + "] Failed to trigger internal reload: " + e.getMessage());
                        }
                    }
                } else if (pluginName.equals("MrCommunityQuest")) {
                    try {
                        
                        java.lang.reflect.Method reloadConfiguration = plugin.getClass().getMethod("reloadConfiguration");
                        reloadConfiguration.invoke(plugin);
                        MrLibConsoleSayer.MrSay_Info("[" + pluginName + "] Triggered internal config reload");
                    } catch (Exception e) {
                        if (plugin.getConfig().getBoolean("Debug.Enabled", false)) {
                            MrLibConsoleSayer.MrSay_Warning("[" + pluginName + "] Failed to trigger internal reload: " + e.getMessage());
                        }
                    }
                }
            });
            
        } catch (Exception e) {
            MrLibConsoleSayer.MrSay_Warning("Failed to download configs: " + e.getMessage());
            MrLibConsoleSayer.MrSay_Warning("Using local configuration files");
            
            createDefaultConfigs();
        }
        */
    }
    
    /**
     * Special download logic for MrUltimateShop
     * - config.yml & messages.yml: normal merge
     * - tracker.yml, sell-gui.yml, sell-all-gui.yml, menu.yml, buy-gui.yml: download only if missing
     * - Shops/: download only on first run (tracked in .shops-downloaded file)
     */
    private void downloadMrUltimateShopConfigs(Map<String, Integer> configVersions) {
        for (Map.Entry<String, Integer> entry : configVersions.entrySet()) {
            String configName = entry.getKey();
            int remoteVersion = entry.getValue();
            
            
            if (configName.equals("config.yml") || configName.equals("messages.yml")) {
                downloadConfig(configName, remoteVersion);
            }
            
            else if (configName.equals("tracker.yml") || configName.equals("sell-gui.yml") || 
                     configName.equals("sell-all-gui.yml") || configName.equals("menu.yml") || 
                     configName.equals("buy-gui.yml")) {
                File configFile = new File(plugin.getDataFolder(), configName);
                if (!configFile.exists()) {
                    downloadConfig(configName, remoteVersion);
                } else {
                    MrLibConsoleSayer.MrSay_Info(configName + " already exists, skipping download");
                }
            }
            
            else if (configName.startsWith("Shops/")) {
                File shopsMarker = new File(plugin.getDataFolder(), ".shops-downloaded");
                if (!shopsMarker.exists()) {
                    
                    downloadConfigWithoutMerge(configName, remoteVersion);
                }
                
                
            }
        }
        
        
        if (configVersions.keySet().stream().anyMatch(name -> name.startsWith("Shops/"))) {
            File shopsMarker = new File(plugin.getDataFolder(), ".shops-downloaded");
            if (!shopsMarker.exists()) {
                try {
                    shopsMarker.createNewFile();
                    MrLibConsoleSayer.MrSay_Info("Shops downloaded - will not download again (even if missing)");
                } catch (Exception e) {
                    
                }
            }
        }
    }
    
    
    /**
     * Special download logic for MrUltimateJobs
     * - config.yml & messages.yml: normal merge
     * - boosters.yml, events.yml, tournaments.yml, data.yml: download only if missing
     * - Menus/*.yml: download only if missing
     * - Jobs/*.yml: download only on first run (tracked in .jobs-downloaded file)
     */
    private void downloadMrUltimateJobsConfigs(Map<String, Integer> configVersions) {
        for (Map.Entry<String, Integer> entry : configVersions.entrySet()) {
            String configName = entry.getKey();
            int remoteVersion = entry.getValue();
            
            
            if (configName.equals("config.yml") || configName.equals("messages.yml")) {
                downloadConfig(configName, remoteVersion);
            }
            
            else if (configName.equals("boosters.yml") || configName.equals("events.yml") || 
                     configName.equals("tournaments.yml") || configName.equals("data.yml")) {
                File configFile = new File(plugin.getDataFolder(), configName);
                if (!configFile.exists()) {
                    downloadConfigWithoutMerge(configName, remoteVersion);
                } else {
                    MrLibConsoleSayer.MrSay_Info(configName + " already exists, skipping download");
                }
            }
            
            else if (configName.startsWith("Menus/")) {
                File configFile = new File(plugin.getDataFolder(), configName);
                if (!configFile.exists()) {
                    downloadConfigWithoutMerge(configName, remoteVersion);
                } else {
                    MrLibConsoleSayer.MrSay_Info(configName + " already exists, skipping download");
                }
            }
            
            else if (configName.startsWith("Jobs/")) {
                File jobsMarker = new File(plugin.getDataFolder(), ".jobs-downloaded");
                if (!jobsMarker.exists()) {
                    
                    downloadConfigWithoutMerge(configName, remoteVersion);
                }
                
                
            }
        }
        
        
        if (configVersions.keySet().stream().anyMatch(name -> name.startsWith("Jobs/"))) {
            File jobsMarker = new File(plugin.getDataFolder(), ".jobs-downloaded");
            if (!jobsMarker.exists()) {
                try {
                    jobsMarker.createNewFile();
                    MrLibConsoleSayer.MrSay_Info("Jobs downloaded - will not download again (even if missing)");
                } catch (Exception e) {
                    
                }
            }
        }
    }
    
    /**
     * Converts old configuration files to new format
     */
    private void convertOldConfigs() {
        try {
            MrLibConfigConverter converter = new MrLibConfigConverter(plugin);
            
            
            String[] configsToConvert;
            if (pluginName.equals("MrUltimateJobs")) {
                configsToConvert = new String[]{"config.yml", "messages.yml"};
            } else {
                configsToConvert = new String[]{"config.yml", "messages.yml", "menu.yml", "boosters.yml"};
            }
            
            for (String configName : configsToConvert) {
                if (converter.needsConversion(configName)) {
                    MrLibConsoleSayer.MrSay_Info("Converting old " + configName + " to new format...");
                    converter.convertConfig(configName);
                }
            }
        } catch (Exception e) {
            
        }
    }
    
    /**
     * Gets the list of available config files and their versions
     */
    private Map<String, Integer> getConfigVersions() {
        Map<String, Integer> versions = new HashMap<>();
        
        try {
            URL url = new URL(BASE_URL + pluginName.toLowerCase() + "/versions.json");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", pluginName + "/" + plugin.getDescription().getVersion());
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                
                String json = response.toString();
                parseVersionsJson(json, versions);
            }
            
        } catch (Exception e) {
            
        }
        
        return versions;
    }
    
    /**
     * Parses versions.json file
     * Format: {"config.yml": 2, "messages.yml": 3, "menu.yml": 1}
     */
    private void parseVersionsJson(String json, Map<String, Integer> versions) {
        try {
            json = json.trim();
            if (json.startsWith("{")) {
                json = json.substring(1);
            }
            if (json.endsWith("}")) {
                json = json.substring(0, json.length() - 1);
            }
            
            String[] entries = json.split(",");
            for (String entry : entries) {
                String[] parts = entry.split(":");
                if (parts.length == 2) {
                    String key = parts[0].trim().replace("\"", "");
                    int version = Integer.parseInt(parts[1].trim());
                    versions.put(key, version);
                }
            }
        } catch (Exception e) {
            
        }
    }
    
    /**
     * Downloads a specific config file
     */
    private void downloadConfig(String configName, int remoteVersion) {
        try {
            File configFile = new File(plugin.getDataFolder(), configName);
            File tempFile = new File(plugin.getDataFolder(), configName + ".remote-temp");
            
            
            if (configName.equals("boosters.yml") && !pluginName.equals("MrUltimateFishing")) {
                return;
            }
            
            
            
            
            boolean isMessagesFile = configName.equals("messages.yml");
            
            
            int localVersion = 0;
            if (configFile.exists()) {
                FileConfiguration localConfig = YamlConfiguration.loadConfiguration(configFile);
                localVersion = localConfig.getInt("MrLibCore-Configs-Version", 0);
                if (localVersion == 0) {
                    
                    String oldVersionKey = configName.replace(".yml", "") + "-version";
                    localVersion = localConfig.getInt(oldVersionKey, 0);
                }
            }
            
            
            if (remoteVersion > localVersion || !configFile.exists()) {
                URL url = new URL(BASE_URL + pluginName.toLowerCase() + "/" + configName);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                
                connection.setRequestMethod("GET");
                connection.setRequestProperty("User-Agent", pluginName + "/" + plugin.getDescription().getVersion());
                connection.setConnectTimeout(TIMEOUT);
                connection.setReadTimeout(TIMEOUT);
                
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    
                    tempFile.getParentFile().mkdirs();
                    
                    
                    try (InputStream inputStream = connection.getInputStream();
                         FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                        
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                    
                    
                    MrLibConfigMerger merger = new MrLibConfigMerger(plugin);
                    
                    if (isMessagesFile) {
                        
                        merger.mergeMessagesOnly(configFile, tempFile, configName);
                        MrLibConsoleSayer.MrSay_Success("Added new messages to " + configName + " (v" + remoteVersion + ", user customizations preserved)");
                    } else {
                        
                        merger.smartMerge(configFile, tempFile, configName);
                        MrLibConsoleSayer.MrSay_Success("Updated " + configName + " to v" + remoteVersion + " (preserved user data)");
                    }
                    
                    
                    tempFile.delete();
                } else {
                    MrLibConsoleSayer.MrSay_Warning("Failed to download " + configName + " (HTTP " + responseCode + ")");
                }
            } else {
                MrLibConsoleSayer.MrSay_Info(configName + " is up to date (v" + localVersion + ")");
            }
            
        } catch (Exception e) {
            MrLibConsoleSayer.MrSay_Warning("Error downloading " + configName + ": " + e.getMessage());
        }
    }
    
    /**
     * Download config file WITHOUT merge (for Jobs/ files)
     */
    private void downloadConfigWithoutMerge(String configName, int remoteVersion) {
        try {
            File configFile = new File(plugin.getDataFolder(), configName);
            
            
            if (configFile.getParentFile() != null) {
                configFile.getParentFile().mkdirs();
            }
            
            URL url = new URL(BASE_URL + pluginName.toLowerCase() + "/" + configName);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", pluginName + "/" + plugin.getDescription().getVersion());
            connection.setConnectTimeout(TIMEOUT);
            connection.setReadTimeout(TIMEOUT);
            
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                
                try (InputStream inputStream = connection.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(configFile)) {
                    
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }
                MrLibConsoleSayer.MrSay_Success("Downloaded " + configName + " (v" + remoteVersion + ")");
            } else {
                MrLibConsoleSayer.MrSay_Warning("Failed to download " + configName + " (HTTP " + responseCode + ")");
            }
            
        } catch (Exception e) {
            MrLibConsoleSayer.MrSay_Warning("Error downloading " + configName + ": " + e.getMessage());
        }
    }
    
    /**
     * Creates default config files if they don't exist
     * This is a fallback when remote download fails
     */
    private void createDefaultConfigs() {
        Bukkit.getScheduler().runTask(plugin, () -> {
            try {
                File configFile = new File(plugin.getDataFolder(), "config.yml");
                if (!configFile.exists()) {
                    plugin.saveDefaultConfig();
                    MrLibConsoleSayer.MrSay_Info("Created default config.yml");
                }
                
                
                File messagesFile = new File(plugin.getDataFolder(), "messages.yml");
                if (!messagesFile.exists() && plugin.getResource("messages.yml") != null) {
                    plugin.saveResource("messages.yml", false);
                    MrLibConsoleSayer.MrSay_Info("Created default messages.yml");
                }
                
                
                for (String fileName : new String[]{"menu.yml", "shops.yml", "items.yml", "boosters.yml"}) {
                    File file = new File(plugin.getDataFolder(), fileName);
                    if (!file.exists() && plugin.getResource(fileName) != null) {
                        plugin.saveResource(fileName, false);
                        MrLibConsoleSayer.MrSay_Info("Created default " + fileName);
                    }
                }
            } catch (Exception e) {
                MrLibConsoleSayer.MrSay_Error("Failed to create default configs: " + e.getMessage());
            }
        });
    }
    
    /**
     * Forces re-download of all config files
     */
    public void forceDownload() {
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            try {
                Map<String, Integer> configVersions = getConfigVersions();
                
                for (Map.Entry<String, Integer> entry : configVersions.entrySet()) {
                    String configName = entry.getKey();
                    int remoteVersion = entry.getValue();
                    
                    
                    File configFile = new File(plugin.getDataFolder(), configName);
                    if (configFile.exists()) {
                        configFile.delete();
                    }
                    
                    downloadConfig(configName, remoteVersion);
                }
                
                MrLibConsoleSayer.MrSay_Success("Force downloaded all configuration files");
                
            } catch (Exception e) {
                MrLibConsoleSayer.MrSay_Error("Force download failed: " + e.getMessage());
            }
        });
    }
}
