package cn.com.poc.ai_software_copyright.agent;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.gsst.dify_client.exception.DifyApiException;
import cn.com.poc.agent_application.entity.AgentResultEntity;
import cn.com.poc.ai_software_copyright.contant.AiSoftWareCopyRightEnum;
import cn.com.poc.ai_software_copyright.domain.BaseInfo;
import cn.com.poc.ai_software_copyright.domain.GeneratedDoc;
import cn.com.poc.ai_software_copyright.domain.TechnicalContent;
import cn.com.poc.ai_software_copyright.factory.DocGenerationStrategyFactory;
import cn.com.poc.ai_software_copyright.utils.SoftwareCopyRightUtils;
import cn.com.poc.common.config.DifyConfigProperties;
import cn.com.poc.common.pool.CommonThreadPoolExecutor;
import cn.com.poc.common.service.impl.DifyChatServiceImpl;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author alex.yao
 * @date 2025/12/29
 */
@Component
public class SoftwareCopyRightAgent {

    private final Logger logger = LoggerFactory.getLogger(SoftwareCopyRightAgent.class);

    @Value("${dify.software_copyright.callball.url}")
    private String CALL_BACK_URL;

    @Resource
    private SoftwareCopyRightUtils softwareCopyRightUtils;

    @Autowired
    private DifyConfigProperties difyConfigProperties;

    @Autowired
    private DifyChatServiceImpl difyChatService;

    @Autowired
    private DocGenerationStrategyFactory docGenerationStrategyFactory;

    /**
     * 软著AI助手
     */
    public void softwareCopyRightAssistant(List<String> fileUrls, String question, Map<String, Object> data)
            throws DifyApiException, IOException, InterruptedException {
        String apiKey = difyConfigProperties.getApiKeys().get("ai-assistant-development-purpose");
        fileUrls = softwareCopyRightUtils.downloadAndUnzipPlugin(fileUrls);
        difyChatService.streamChat(
                fileUrls,
                question,
                data,
                "ai-assistant-development-purpose",
                apiKey
        );
    }

    /**
     * 生成基础文档
     *
     * @param taskId
     * @param files
     * @param baseInfo
     * @param technicalContent
     */
    public void generatedBaseDoc(String taskId, List<String> files, BaseInfo baseInfo,
                                 TechnicalContent technicalContent) {
        String apiKey = difyConfigProperties.getApiKeys().get("generated-base-doc");
        String ques = "执行";
        String user = "generatedBaseDoc" + DateUtils.getCurrTime();
        List<String> filesURL = softwareCopyRightUtils.downloadAndUnzipPlugin(files);

        Map<String, Object> data = new HashMap<>();
        data.put("task_id", taskId);
        data.put("baseinfo", JsonUtils.serialize(baseInfo));
        data.put("technical_content", JsonUtils.serialize(technicalContent));
        data.put("callback_url", CALL_BACK_URL);
        CommonThreadPoolExecutor.addTask(() -> {
            try {
                difyChatService.blockingChat(filesURL, ques, data, user, apiKey);
            } catch (Exception e) {
                logger.error("生成基础文档失败: {}", e.getMessage(), e);
                throw new BusinessException("生成基础文档失败", e);
            }
        });
    }


    /**
     * 文件生成
     *
     * @param generatedDoc
     * @param docType
     * @return
     */
    public void generatedDocByType(GeneratedDoc generatedDoc, AiSoftWareCopyRightEnum.DOC_TYPE docType) {
        docGenerationStrategyFactory.getStrategy(docType).generate(generatedDoc);
    }

    /**
     * 软著AI助手-技术内容生成
     *
     * @param fileUrls
     * @param query
     * @param data     - files 除源代码以外的文档内容 / code - 源代码
     * @return
     */
    public String technicalContent(List<String> fileUrls, String query, Map<String, Object> data) {
        String apiKey = difyConfigProperties.getApiKeys().get("technical-content");
        String user = "user-technicalContent";

        try {
            AgentResultEntity response = difyChatService.blockingChat(
                    fileUrls,
                    query,
                    data,
                    user,
                    apiKey
            );
            return response.getMessage();
        } catch (Exception e) {
            logger.error("执行【技术内容】生成异常: {}", e.getMessage(), e);
            throw new BusinessException("执行【技术内容】生成异常", e);
        }
    }
}
