package org.xyzh.ai.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.context.annotation.Configuration;
import org.xyzh.api.system.service.SysConfigService;

import jakarta.annotation.PostConstruct;

/**
 * @description Dify配置类
 * @filename DifyConfig.java
 * @author AI Assistant
 * @copyright xyzh
 * @since 2025-11-04
 */
@Slf4j
@Data
@Configuration
public class DifyConfig {

    @DubboReference(version = "1.0.0", group = "system", timeout = 30000, retries = 0)
    private SysConfigService sysConfigService;

    /**
     * Dify API基础地址
     */
    private String apiBaseUrl = "http://192.168.130.131/v1";

    private String knowledgeApiKey="dataset-nupqKP4LONpzdXmGthIrbjeJ";

    /**
     * 请求超时时间（秒）
     */
    private Integer timeout = 60;

    /**
     * 连接超时时间（秒）
     */
    private Integer connectTimeout = 10;

    /**
     * 读取超时时间（秒）
     */
    private Integer readTimeout = 60;

    /**
     * 流式响应超时时间（秒）
     */
    private Integer streamTimeout = 300;

    /**
     * 上传文件配置
     */
    private Upload upload = new Upload();

    /**
     * 知识库配置
     */
    private Dataset dataset = new Dataset();

    /**
     * 初始化配置，从数据库加载
     */
    @PostConstruct
    public void init() {
        try {
            log.info("开始从数据库加载Dify配置...");
            
            // 基础配置
            loadStringConfig("dify.apiBaseUrl", val -> this.apiBaseUrl = val);
            loadStringConfig("dify.knowledgeApiKey", val -> this.knowledgeApiKey = val);
            loadIntegerConfig("dify.timeout", val -> this.timeout = val);
            loadIntegerConfig("dify.connectTimeout", val -> this.connectTimeout = val);
            loadIntegerConfig("dify.readTimeout", val -> this.readTimeout = val);
            loadIntegerConfig("dify.streamTimeout", val -> this.streamTimeout = val);
            
            // Upload配置
            loadStringConfig("dify.upload.allowedTypes", val -> {
                if (val != null && !val.trim().isEmpty()) {
                    this.upload.allowedTypes = val.split(",");
                }
            });
            loadIntegerConfig("dify.upload.maxSize", val -> this.upload.maxSize = val);
            
            // Dataset配置
            loadStringConfig("dify.dataset.defaultIndexingTechnique", val -> this.dataset.defaultIndexingTechnique = val);
            loadStringConfig("dify.dataset.defaultEmbeddingModel", val -> this.dataset.defaultEmbeddingModel = val);
            
            log.info("Dify配置加载完成 - API地址: {}", apiBaseUrl);
        } catch (Exception e) {
            log.error("加载Dify配置失败，将使用默认值", e);
        }
    }
    
    /**
     * 加载字符串配置
     */
    private void loadStringConfig(String key, java.util.function.Consumer<String> setter) {
        try {
            String value = sysConfigService.getStringConfig(key);
            if (value != null && !value.trim().isEmpty()) {
                setter.accept(value);
                log.debug("加载配置: {} = {}", key, value);
            }
        } catch (Exception e) {
            log.warn("加载配置失败: {}, 错误: {}", key, e.getMessage());
        }
    }
    
    /**
     * 加载整数配置
     */
    private void loadIntegerConfig(String key, java.util.function.Consumer<Integer> setter) {
        try {
            Integer value = sysConfigService.getIntConfig(key);
            if (value != null) {
                setter.accept(value);
                log.debug("加载配置: {} = {}", key, value);
            }
        } catch (Exception e) {
            log.warn("加载配置失败: {}, 错误: {}", key, e.getMessage());
        }
    }

    @Data
    public static class Upload {
        /**
         * 支持的文件类型
         */
        private String[] allowedTypes = {"pdf", "txt", "docx", "doc", "md", "html", "htm"};

        /**
         * 最大文件大小（MB）
         */
        private Integer maxSize = 50;
    }

    @Data
    public static class Dataset {
        /**
         * 默认索引方式（high_quality/economy）
         */
        private String defaultIndexingTechnique = "high_quality";

        /**
         * 默认Embedding模型
         */
        private String defaultEmbeddingModel = "text-embedding-ada-002";
    }

    /**
     * 验证配置是否有效
     */
    public boolean isValid() {
        return apiBaseUrl != null && !apiBaseUrl.trim().isEmpty();
    }

    /**
     * 获取完整的API URL
     */
    public String getFullApiUrl(String endpoint) {
        String baseUrl = apiBaseUrl.endsWith("/") ? apiBaseUrl.substring(0, apiBaseUrl.length() - 1) : apiBaseUrl;
        String path = endpoint.startsWith("/") ? endpoint : "/" + endpoint;
        return baseUrl + path;
    }
}

