package top.gtb520.java.pve_back_api.config;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

/**
 * YAML配置文件解析器
 * 负责从不同来源加载和解析YAML配置文件
 */
public class YamlConfigLoader {
    
    private static final String GLOBAL_SECTION = "global";
    private static final String DATABASE_SECTION = "database";
    private static final String PVE_SECTION = "pve";
    
    /**
     * 从资源文件加载配置
     * @param resourcePath 资源文件路径
     */
    public static void loadConfigFromResource(String resourcePath) {
        try {
            Yaml yaml = new Yaml();
            InputStream inputStream = YamlConfigLoader.class.getClassLoader().getResourceAsStream(resourcePath);

            if (inputStream == null) {
                handleResourceNotFound(resourcePath);
                return;
            }

            Map<String, Object> data = yaml.load(inputStream);
            parseConfig(data);

        } catch (Exception e) {
            handleLoadException("资源", resourcePath, e);
        }
    }

    /**
     * 从文件路径加载配置
     * @param filePath 文件路径
     */
    public static void loadConfigFromFile(String filePath) {
        try {
            Yaml yaml = new Yaml();
            InputStream inputStream = java.nio.file.Files.newInputStream(java.nio.file.Paths.get(filePath));

            Map<String, Object> data = yaml.load(inputStream);
            parseConfig(data);

        } catch (Exception e) {
            handleLoadException("文件", filePath, e);
        }
    }

    /**
     * 解析配置数据并设置到全局变量
     * @param data 配置数据映射
     */
    @SuppressWarnings("unchecked")
    private static void parseConfig(Map<String, Object> data) {
        try {
            parseGlobalConfig(data);
            parseDatabaseConfig(data);
            parsePveConfig(data);

            System.out.println("配置加载成功!");
            GlobalConfig.printConfig();

        } catch (Exception e) {
            System.err.println("解析配置数据时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 解析全局配置部分
     */
    private static void parseGlobalConfig(Map<String, Object> data) {
        if (!data.containsKey(GLOBAL_SECTION)) {
            return;
        }
        
        @SuppressWarnings("unchecked")
        Map<String, Object> global = (Map<String, Object>) data.get(GLOBAL_SECTION);
        GlobalConfig.HTTP_IP = getStringValue(global, "http_ip", GlobalConfig.HTTP_IP);
        GlobalConfig.HTTP_PORT = getStringValue(global, "http_port", GlobalConfig.HTTP_PORT);
    }
    
    /**
     * 解析数据库配置部分
     */
    private static void parseDatabaseConfig(Map<String, Object> data) {
        if (!data.containsKey(DATABASE_SECTION)) {
            return;
        }
        
        @SuppressWarnings("unchecked")
        Map<String, Object> database = (Map<String, Object>) data.get(DATABASE_SECTION);
        GlobalConfig.MYSQL_JDBC = getStringValue(database, "mysql_jdbc", GlobalConfig.MYSQL_JDBC);
        GlobalConfig.MYSQL_USERNAME = getStringValue(database, "mysql_username", GlobalConfig.MYSQL_USERNAME);
        GlobalConfig.MYSQL_PASSWORD = getStringValue(database, "mysql_password", GlobalConfig.MYSQL_PASSWORD);
    }
    
    /**
     * 解析PVE配置部分
     */
    private static void parsePveConfig(Map<String, Object> data) {
        if (!data.containsKey(PVE_SECTION)) {
            return;
        }
        
        @SuppressWarnings("unchecked")
        Map<String, Object> pve = (Map<String, Object>) data.get(PVE_SECTION);
        GlobalConfig.PVE_URL = getStringValue(pve, "url", GlobalConfig.PVE_URL);
        GlobalConfig.PVE_API_TOKEN_NAME = getStringValue(pve, "api_tocken_name", GlobalConfig.PVE_API_TOKEN_NAME);
        GlobalConfig.PVE_API_TOKEN_ID = getStringValue(pve, "api_token_id", GlobalConfig.PVE_API_TOKEN_ID);
        GlobalConfig.PVE_API_TOKEN_SECRET = getStringValue(pve, "api_token_secret", GlobalConfig.PVE_API_TOKEN_SECRET);
    }
    
    /**
     * 安全获取字符串值
     */
    private static String getStringValue(Map<String, Object> map, String key, String defaultValue) {
        if (map.containsKey(key)) {
            Object value = map.get(key);
            return value != null ? value.toString() : defaultValue;
        }
        return defaultValue;
    }
    
    /**
     * 处理资源未找到的情况
     */
    private static void handleResourceNotFound(String resourcePath) {
        System.err.println("❌ 无法找到资源配置文件: " + resourcePath);
    }
    
    /**
     * 处理加载异常
     */
    private static void handleLoadException(String type, String path, Exception e) {
        System.err.println("❌ 解析" + type + "配置文件失败: " + path);
        System.err.println("错误详情: " + e.getMessage());
        e.printStackTrace();
    }
}
