package org.dromara.system.ai.splitter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringEscapeUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.AiKnowledgeInfoDo;
import org.dromara.system.domain.vo.AiKnowledgeInfoVo;
import org.dromara.system.mapper.AiKnowledgeInfoMapper;
import org.dromara.system.service.IAiKnowledgeInfoService;
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
    private final AiKnowledgeInfoMapper knowledgeInfoMapper;

    public CharacterTextSplitter(AiKnowledgeInfoMapper knowledgeInfoMapper) {
        this.knowledgeInfoMapper = knowledgeInfoMapper;
    }

    @Override
    public List<String> split(String content, String kid) {
        // 从知识库表中获取配置
        AiKnowledgeInfoVo aiKnowledgeInfoVo = knowledgeInfoMapper.selectVoOne(
            new LambdaQueryWrapper<AiKnowledgeInfoDo>().eq(AiKnowledgeInfoDo::getKnowledgeCode, kid));
        String knowledgeSeparator = aiKnowledgeInfoVo.getKnowledgeSeparator();
        int textBlockSize = aiKnowledgeInfoVo.getTextBlockSize();
        int overlapChar = aiKnowledgeInfoVo.getOverlapChar();
        List<String> chunkList = new ArrayList<>();
        if (content.contains(StringEscapeUtils.unescapeJava(knowledgeSeparator)) && StringUtils.isNotBlank(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;
    }
}
