package org.xyzh.workcase.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xyzh.api.ai.dto.TbAgent;
import org.xyzh.api.ai.dto.TbKnowledge;
import org.xyzh.api.ai.service.AgentService;
import org.xyzh.api.ai.service.KnowledgeService;
import org.xyzh.api.system.service.SysConfigService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.utils.id.IdUtil;

/**
 * @description    初始化客服系统必须的8个知识库，4个内部知识库，4个外部知识库，运行结束即销毁
 * @filename    KnowledgeInit.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-18
 */
@Configuration
public class AiInit {
    private static final Logger logger = LoggerFactory.getLogger(AiInit.class);

    private static final String SERVICE_WORKCASE = "workcase";
    private static final String CATEGORY_INTERNAL = "internal";
    private static final String CATEGORY_EXTERNAL = "external";

    @DubboReference(version = "1.0.0", group = "ai", timeout = 30000, retries = 0)
    private KnowledgeService knowledgeService;

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

    @DubboReference(version = "1.0.0", group = "ai", timeout = 30000, retries = 0)
    private AgentService agentService;

    @Bean
    public CommandLineRunner knowledgeInitRunner() {
        return args -> {
            logger.info("开始初始化客服系统知识库...");
            
            List<TbKnowledge> knowledges = buildKnowledgeConfigs();
            int successCount = 0;
            int skipCount = 0;
            for(TbKnowledge knowledge : knowledges){
                if(!checkKnowledgeExists(knowledge.getKnowledgeId())){
                    if(createKnowledge(knowledge)){
                        successCount++;
                    }
                }else{
                    skipCount++;
                }
            }
            
            logger.info("客服系统知识库初始化完成: 成功创建{}个，跳过{}个", successCount, skipCount);
        };
    }

    @Bean
    public CommandLineRunner agentInitRunner(){
        return args -> {
            logger.info("开始初始化客服系统智能体...");
            TbAgent agent = new TbAgent();
            agent.setIsOuter(true);
            agent.setName("泰豪小电");
            ResultDomain<TbAgent> listDomain = agentService.getAgentList(agent);
            if (listDomain.getSuccess()&&!listDomain.getDataList().isEmpty()) {
                logger.info("泰豪小电智能体已经存在");
                return;
            }
            agent.setApiKey("app-CDKy0wYkPnl6dA6G7eu113Vw");
            agent.setIntroduce("您好，我是泰豪小电智能客服。请描述您的问题，我会尽力协助。");
            agent.setCategory("客服智能体");
            agent.setCategory("user_admin");
            ResultDomain<TbAgent> resultDomain = agentService.addAgent(agent);
            if(resultDomain.getSuccess()){
                logger.info("泰豪小电智能体初始化成功");
            }else{
                logger.error("泰豪小电智能体初始化失败"+resultDomain.getMessage());
            }
        };
    }

    /**
     * 构建8个知识库配置
     */
    private List<TbKnowledge> buildKnowledgeConfigs() {
        List<TbKnowledge> knowledges = new ArrayList<>();
        // 从数据库获取知识库配置默认信息
        TbKnowledge baseKnowledge = new TbKnowledge();
        baseKnowledge.setDifyIndexingTechnique(sysConfigService.getStringConfig("dify.knowledge.indexing.tchnique"));
        baseKnowledge.setEmbeddingModel(sysConfigService.getStringConfig("dify.knowledge.embedding.model"));
        baseKnowledge.setEmbeddingModelProvider(sysConfigService.getStringConfig("dify.knowledge.embedding.model.provider"));
        baseKnowledge.setRerankingEnable(sysConfigService.getBooleanConfig("dify.knowledge.reranking.enable"));
        baseKnowledge.setRerankModel(sysConfigService.getStringConfig("dify.knowledge.rerank.model"));
        baseKnowledge.setRerankModelProvider(sysConfigService.getStringConfig("dify.knowledge.rerank.model.provider"));
        baseKnowledge.setRetrievalTopK(sysConfigService.getIntConfig("dify.knowledge.retrieval.top.k"));
        baseKnowledge.setRetrievalScoreThreshold(sysConfigService.getDoubleConfig("dify.knowledge.retrieval.score.threshold"));


        // 外部知识库
        TbKnowledge outerDevOperKnowledge = new TbKnowledge();
        outerDevOperKnowledge.setKnowledgeId("workcase_outer_device_operate");
        outerDevOperKnowledge.setTitle("设备操作指南");
        outerDevOperKnowledge.setAvatar("settings");
        outerDevOperKnowledge.setCategory(CATEGORY_EXTERNAL);
        knowledges.add(outerDevOperKnowledge);

        TbKnowledge outerCommonErrorKnowledge = new TbKnowledge();
        outerCommonErrorKnowledge.setKnowledgeId("workcase_outer_common_error");
        outerCommonErrorKnowledge.setTitle("常见故障解决方案");
        outerCommonErrorKnowledge.setAvatar("question");
        outerCommonErrorKnowledge.setCategory(CATEGORY_EXTERNAL);
        knowledges.add(outerCommonErrorKnowledge);

        TbKnowledge outerSanBaoKnowledge = new TbKnowledge();
        outerSanBaoKnowledge.setKnowledgeId("workcase_outer_sanbao");
        outerSanBaoKnowledge.setTitle("三包外服务政策");
        outerSanBaoKnowledge.setAvatar("document");
        outerSanBaoKnowledge.setCategory(CATEGORY_EXTERNAL);
        knowledges.add(outerSanBaoKnowledge);

        TbKnowledge outerMountingsKnowledge = new TbKnowledge();
        outerMountingsKnowledge.setKnowledgeId("workcase_outer_mounting_chat");
        outerMountingsKnowledge.setTitle("配件咨询话术");
        outerMountingsKnowledge.setAvatar("chat");
        outerMountingsKnowledge.setCategory(CATEGORY_EXTERNAL);
        knowledges.add(outerMountingsKnowledge);

        // 内部知识库
        TbKnowledge innerDevFixKnowledge = new TbKnowledge();
        innerDevFixKnowledge.setKnowledgeId("workcase_inner_device_fix");
        innerDevFixKnowledge.setTitle("技术维修手册");
        innerDevFixKnowledge.setAvatar("settings");
        innerDevFixKnowledge.setCategory(CATEGORY_INTERNAL);
        knowledges.add(innerDevFixKnowledge);

        TbKnowledge innerProArgsKnowledge = new TbKnowledge();
        innerProArgsKnowledge.setKnowledgeId("workcase_inner_product_args_info");
        innerProArgsKnowledge.setTitle("产品参数明细");
        innerProArgsKnowledge.setAvatar("document");
        innerProArgsKnowledge.setCategory(CATEGORY_INTERNAL);
        knowledges.add(innerProArgsKnowledge);

        TbKnowledge innerServExpKnowledge = new TbKnowledge();
        innerServExpKnowledge.setKnowledgeId("workcase_inner_service_exp");
        innerServExpKnowledge.setTitle("内部服务流程规范");
        innerServExpKnowledge.setAvatar("document");
        innerServExpKnowledge.setCategory(CATEGORY_INTERNAL);
        knowledges.add(innerServExpKnowledge);

        TbKnowledge innerServChatKnowledge = new TbKnowledge();
        innerServChatKnowledge.setKnowledgeId("workcase_inner_service_chat");
        innerServChatKnowledge.setTitle("客户服务话术模板");
        innerServChatKnowledge.setAvatar("chat");
        innerServChatKnowledge.setCategory(CATEGORY_INTERNAL);
        knowledges.add(innerServChatKnowledge);

        // 统一设置dify知识库相关参数,并设置service为workcase
        for(TbKnowledge knowledge: knowledges){
            knowledge.setService(SERVICE_WORKCASE);
            knowledge.setOptsn(IdUtil.getOptsn());
            // 从baseKnowledge同步知识库默认配置
            knowledge.setDifyIndexingTechnique(baseKnowledge.getDifyIndexingTechnique());
            knowledge.setEmbeddingModel(baseKnowledge.getEmbeddingModel());
            knowledge.setEmbeddingModelProvider(baseKnowledge.getEmbeddingModelProvider());
            knowledge.setRerankingEnable(baseKnowledge.getRerankingEnable());
            knowledge.setRerankModel(baseKnowledge.getRerankModel());
            knowledge.setRerankModelProvider(baseKnowledge.getRerankModelProvider());
            knowledge.setRetrievalTopK(baseKnowledge.getRetrievalTopK());
            knowledge.setRetrievalScoreThreshold(baseKnowledge.getRetrievalScoreThreshold());
        }
        
        return knowledges;
    }

    private boolean checkKnowledgeExists(String knowledgeId){
        ResultDomain<TbKnowledge> knowledge = knowledgeService.getKnowledgeById(knowledgeId);
        if(knowledge.getSuccess() && knowledge.getData() != null){
            return true;
        }
        return false;
    }

    /**
     * 创建知识库
     */
    private boolean createKnowledge(TbKnowledge knowledge) {
        
        ResultDomain<TbKnowledge> result = knowledgeService.createKnowledgeInternal(knowledge);
        
        if (result.getSuccess()) {
            logger.info("创建知识库成功: {} [{}]", knowledge.getTitle(), knowledge.getCategory());
            return true;
        } else {
            logger.error("创建知识库失败: {} - {}", knowledge.getTitle(), result.getMessage());
            return false;
        }
    }
}
