package cn.com.poc.ai_software_copyright.aggregate.impl;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.gsst.dify_client.exception.DifyApiException;
import cn.com.poc.ai_software_copyright.agent.SoftwareCopyRightAgent;
import cn.com.poc.ai_software_copyright.aggregate.SoftwareCopyRightService;
import cn.com.poc.ai_software_copyright.contant.AiSoftWareCopyRightEnum;
import cn.com.poc.ai_software_copyright.domian.BaseInfo;
import cn.com.poc.ai_software_copyright.domian.TechnicalContent;
import cn.com.poc.common.utils.DocumentLoad;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.poc.common.utils.StringUtils;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author alex.yao
 * @date 2025/12/26
 */
@Service
public class SoftwareCopyRightServiceImpl implements SoftwareCopyRightService {

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

    @Resource
    private SoftwareCopyRightAgent softwareCopyRightAgent;

    @Override
    public void softwareCopyRightAssistant(
            AiSoftWareCopyRightEnum.AI_ASSISTANT_TYPE type,
            List<String> fileUrls,
            String question,
            Map<String, Object> data
    ) throws InterruptedException, DifyApiException, IOException {
        switch (type) {
            case MAIN_FUNCTION:
                softwareCopyRightAgent.mainFunction(fileUrls, "生成[开发目的]", data);
                break;
            case TARGET_INDUSTRY:
                softwareCopyRightAgent.targetIndustry(fileUrls, "生成[面向行业/领域]", data);
                break;
            case TECHNICAL_FEATURES:
                softwareCopyRightAgent.technicalFeatures(fileUrls, "生成[软件的主要功能]", data);
                break;
            case DEVELOPMENT_PURPOSE:
                softwareCopyRightAgent.developmentPurpose(fileUrls, "生成[技术特点]", data);
                break;
            default:
                throw new BusinessException("不支持的AI助手类型: " + type);
        }
    }

    @Override
    public TechnicalContent createTechnicalContent(List<String> fileUrls, BaseInfo baseInfo) throws IOException {
        Map<String, Object> data = new HashMap<>();
        // 下载文件内容
        if (CollectionUtils.isNotEmpty(fileUrls)) {
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder codeBuilder = new StringBuilder();
            for (String fileUrl : fileUrls) {
                File file = DocumentLoad.downloadURLDocument(fileUrl);

                // 判断是否为压缩文件并解压
                if (isCompressedFile(file)) {
                    //todo 解压文件，获取解压后的文件列表
                    List<File> files = unGzip(file);
                    for (File codeFiles : files) {
//                        String fileContent = DocumentLoad.documentToText(codeFiles);
//                        codeBuilder.append("##").append(file.getName()).append(StringUtils.LF);
//                        codeBuilder.append(fileContent).append(StringUtils.LF);
                    }

                } else {
                    String fileContent = DocumentLoad.documentToText(file);
                    stringBuilder.append("##").append(file.getName()).append(StringUtils.LF);
                    stringBuilder.append(fileContent).append(StringUtils.LF);
                }
            }
            data.put("files", stringBuilder.toString());
            data.put("code", codeBuilder.toString());
        }
        String baseInfoStr = JsonUtils.serialize(baseInfo);
        String technicalContent = softwareCopyRightAgent.technicalContent(null, baseInfoStr, data);
        logger.info("【技术内容】 baseInfo:{},生成结果: {}", baseInfoStr, technicalContent);
        if (StringUtils.isBlank(technicalContent)) {
            throw new BusinessException("执行【技术内容】生成异常");
        }
        return JsonUtils.deSerialize(technicalContent, TechnicalContent.class);
    }

    /**
     * 判断文件是否为压缩文件
     *
     * @param file 文件
     * @return 是否为压缩文件
     */
    private boolean isCompressedFile(File file) {
        String fileName = file.getName().toLowerCase();
        return fileName.endsWith(".zip") || fileName.endsWith(".tar") ||
                fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz") ||
                fileName.endsWith(".rar") || fileName.endsWith(".7z");
    }

    /**
     * 解压文件
     *
     * @param gzipFile
     * @return
     * @throws IOException
     */
    private List<File> unGzip(File gzipFile) throws IOException {
        // 目标解压目录
        String destDir = Files.createTempDirectory("gzip/temp/").toString();
        // 确保目标目录存在
        FileUtil.mkdir(destDir);
        File[] extractedFiles = ZipUtil.unzip(gzipFile, new File(destDir)).listFiles();
        return ListUtil.toList(extractedFiles);
    }

}