package com.emoon.knowledge.chain.split;

import com.emoon.common.core.utils.StringUtils;
import com.emoon.knowledge.domain.vo.KnowledgeInfoVo;
import com.emoon.knowledge.service.IKnowledgeInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

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

@Component
@Slf4j
@Primary
public class CharacterTextSplitter implements TextSplitter {

    @Lazy
    @Resource
    private IKnowledgeInfoService knowledgeInfoService;

    @Override
    public List<String> split(String content, String kid) {
        // 从知识库表中获取配置
        // kid 可能是 id（数字）或 kid（字符串），先尝试通过 id 查询，失败则通过 kid 查询
        KnowledgeInfoVo knowledgeInfoVo = null;
        try {
            Long knowledgeId = Long.valueOf(kid);
            knowledgeInfoVo = knowledgeInfoService.queryById(knowledgeId);
        } catch (NumberFormatException e) {
            // 如果不是数字，则通过 kid 查询
            com.emoon.knowledge.domain.bo.KnowledgeInfoBo bo = new com.emoon.knowledge.domain.bo.KnowledgeInfoBo();
            bo.setKid(kid);
            java.util.List<KnowledgeInfoVo> list = knowledgeInfoService.queryList(bo);
            if (list != null && !list.isEmpty()) {
                knowledgeInfoVo = list.get(0);
            }
        }
        
        if (knowledgeInfoVo == null) {
            throw new RuntimeException("未找到知识库信息，kid: " + kid);
        }
        
        String knowledgeSeparator = knowledgeInfoVo.getKnowledgeSeparator();
        int textBlockSize = Math.toIntExact((knowledgeInfoVo.getTextBlockSize()));
        int overlapChar = Math.toIntExact(knowledgeInfoVo.getOverlapChar());
        List<String> chunkList = new ArrayList<>();
        
        // 先检查分隔符是否为空，如果不为空且内容包含该分隔符，则按分隔符切分
        if (StringUtils.isNotBlank(knowledgeSeparator) && content.contains(StringEscapeUtils.unescapeJava(knowledgeSeparator))) {
            // 按自定义分隔符切分
            String[] chunks = content.split(StringEscapeUtils.unescapeJava(knowledgeSeparator));
            chunkList.addAll(Arrays.asList(chunks));
        } else {
            // 如果没有分隔符或内容不包含分隔符，则按字数切割
            int indexMin = 0;
            int len = content.length();
            int i = 0;
            int right = 0;
            while (true) {
                if (len > right) {
                    int begin = i * textBlockSize - overlapChar;
                    if (begin < indexMin) {
                        begin = indexMin;
                    }
                    int end = textBlockSize * (i + 1) + overlapChar;
                    if (end > len) {
                        end = len;
                    }
                    String chunk = content.substring(begin, end);
                    chunkList.add(chunk);
                    i++;
                    right = right + textBlockSize;
                } else {
                    break;
                }
            }
        }
        return chunkList;
    }
}
