package cn.com.poc.ai_software_copyright.agent;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import cn.com.gsst.dify_client.DifyChatClient;
import cn.com.gsst.dify_client.DifyClientFactory;
import cn.com.gsst.dify_client.callback.ChatStreamCallback;
import cn.com.gsst.dify_client.enums.FileTransferMethod;
import cn.com.gsst.dify_client.enums.FileType;
import cn.com.gsst.dify_client.enums.ResponseMode;
import cn.com.gsst.dify_client.event.MessageEndEvent;
import cn.com.gsst.dify_client.event.MessageEvent;
import cn.com.gsst.dify_client.exception.DifyApiException;
import cn.com.gsst.dify_client.model.chat.ChatMessage;
import cn.com.gsst.dify_client.model.chat.ChatMessageResponse;
import cn.com.gsst.dify_client.model.file.FileInfo;
import cn.com.poc.ai_software_copyright.contant.AiSoftWareCopyRightEnum;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.SSEUtil;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.thirdparty.resource.demand.ai.entity.largemodel.LargeModelDemandResult;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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


    private static String DIFY_BASE_URL = "https://dify.gsstcloud.com/v1";

    /**
     * 文件生成
     *
     * @param o
     * @param docType
     * @return
     */
    public Object generatedDocByType(Object o, AiSoftWareCopyRightEnum.DOC_TYPE docType) {

        switch (docType) {
            case source_code:
                return sourceCode(o);
            case ph_operating_manual:
                return phOperatingManual(o);
            case pc_operating_manual:
                return pcOperatingManual(o);
            case information:
                return information(o);
            default:
                throw new BusinessException("不支持的文档类型：" + docType);
        }
    }

    /**
     * 软著AI助手-技术内容生成
     *
     * @param fileUrls
     * @param query
     * @param data  - files 除源代码以外的文档内容 / code - 源代码
     * @return
     */
    public String technicalContent(List<String> fileUrls, String query, Map<String, Object> data) {

        DifyChatClient chatClient = DifyClientFactory.createChatClient(DIFY_BASE_URL, "app-VuwhZGr7UqFb2gkg7jOmibGM");

        List<FileInfo> files = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(fileUrls)) {
            for (String fileUrl : fileUrls) {
                files.add(FileInfo.builder()
                        .type(FileType.DOCUMENT)
                        .url(fileUrl)
                        .transferMethod(FileTransferMethod.REMOTE_URL)
                        .build());
            }
        }

        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query(query)
                .user("user-technicalContent")
                .files(files)
                .inputs(data)
                .responseMode(ResponseMode.BLOCKING)
                .build();

        // 发送消息并获取响应
        try {
            ChatMessageResponse chatMessageResponse = chatClient.sendChatMessage(message);
            return chatMessageResponse.getAnswer();
        } catch (IOException | DifyApiException e) {
            throw new BusinessException("执行【技术内容】生成异常");
        }
    }

        // 软著AI助手-源代码生成
        public Object sourceCode(Object o) {
            return null;
        }

        // 软著AI助手-手机端说明书
        public Object phOperatingManual(Object o) {
            return null;
        }

        // 软著AI助手-PC端说明书
        public Object pcOperatingManual(Object o) {
            return null;
        }

        // 软著AI助手-信息采集表
        public Object information(Object o) {
            return null;
        }

    // ------------
    // 软著AI助手-开发目的

    private final String API_KEY = "app-S3y8vmyX95cTa0sb9V9oBfSX";
    public void developmentPurpose(List<String> fileUrls, String question, Map<String, Object> data)
            throws InterruptedException, DifyApiException, IOException {
         streamChat(
                fileUrls,
                question,
                data,
                AiSoftWareCopyRightEnum.AI_ASSISTANT_TYPE.DEVELOPMENT_PURPOSE.name(),
                API_KEY
        );
    }

    // 软著AI助手-面向行业/领域
    public void targetIndustry(List<String> fileUrls, String question, Map<String, Object> data)
            throws InterruptedException, DifyApiException, IOException {
         streamChat(
                fileUrls,
                question,
                data,
                AiSoftWareCopyRightEnum.AI_ASSISTANT_TYPE.TARGET_INDUSTRY.name(),
                API_KEY
        );
    }

    // 软著AI助手-软件的主要功能
    public void mainFunction(List<String> fileUrls, String question, Map<String, Object> data)
            throws InterruptedException, DifyApiException, IOException {
         streamChat(
                fileUrls,
                question,
                data,
                AiSoftWareCopyRightEnum.AI_ASSISTANT_TYPE.MAIN_FUNCTION.name(),
                API_KEY
        );
    }

    // 软著AI助手-该软件的技术特点
    public void technicalFeatures(List<String> fileUrls, String question, Map<String, Object> data)
            throws InterruptedException, DifyApiException, IOException {
        streamChat(
                fileUrls,
                question,
                data,
                AiSoftWareCopyRightEnum.AI_ASSISTANT_TYPE.TECHNICAL_FEATURES.name(),
                API_KEY
        );
    }

    private String blockingChat(List<String> fileUrls,
                                String question,
                                Map<String, Object> data,
                                String user,
                                String apiKey) {
        DifyChatClient chatClient = DifyClientFactory.createChatClient(DIFY_BASE_URL, apiKey);

        List<FileInfo> files = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(fileUrls)) {
            for (String fileUrl : fileUrls) {
                files.add(FileInfo.builder()
                        .type(FileType.DOCUMENT)
                        .url(fileUrl)
                        .transferMethod(FileTransferMethod.REMOTE_URL)
                        .build());
            }
        }

        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query(question)
                .user(user)
                .files(files)
                .inputs(data)
                .responseMode(ResponseMode.BLOCKING)
                .build();

        // 发送消息并获取响应
        try {
            ChatMessageResponse chatMessageResponse = chatClient.sendChatMessage(message);
            return chatMessageResponse.getAnswer();
        } catch (IOException | DifyApiException e) {
            throw new BusinessException("执行" + user + "生成异常");
        }
    }

    private void streamChat(List<String> fileUrls,
                            String question,
                            Map<String, Object> data,
                            String user,
                            String apiKey) throws InterruptedException, IOException, DifyApiException {
        // 创建聊天客户端
        DifyChatClient chatClient = DifyClientFactory.createChatClient(DIFY_BASE_URL, apiKey);

        List<FileInfo> files = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(fileUrls)) {
            for (String fileUrl : fileUrls) {
                files.add(FileInfo.builder()
                        .type(FileType.DOCUMENT)
                        .url(fileUrl)
                        .transferMethod(FileTransferMethod.REMOTE_URL)
                        .build());
            }
        }


        // 创建聊天消息
        ChatMessage message = ChatMessage.builder()
                .query(question)
                .user(user)
                .files(files)
                .inputs(data)
                .responseMode(ResponseMode.STREAMING)
                .build();

        CountDownLatch countDownLatch = new CountDownLatch(1);
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        // 发送消息并获取响应
        chatClient.sendChatMessageStream(message, new ChatStreamCallback() {
            SSEUtil sseUtil = new SSEUtil(response);

            @Override
            public void onMessage(MessageEvent event) {
                try {
                    if (StringUtils.isNotEmpty(event.getAnswer())) {
                        LargeModelDemandResult largeModelDemandResult = new LargeModelDemandResult();
                        largeModelDemandResult.setCode("0");
                        largeModelDemandResult.setMessage(event.getAnswer());
                        sseUtil.send(JsonUtils.serialize(event.getAnswer()));
                    }
                } catch (IOException e) {
                    sseUtil.completeByError(e.getMessage());
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onMessageEnd(MessageEndEvent event) {
                try {
                    sseUtil.send("[DONE]");
                } catch (IOException e) {
                    sseUtil.completeByError(e.getMessage());
                    throw new RuntimeException(e);
                } finally {
                    sseUtil.complete();
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await(60, TimeUnit.SECONDS);
    }
}
