package com.emoon.knowledge.chain.loader;

import com.emoon.knowledge.chain.split.TextSplitter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Markdown 文件加载器
 * 对应原 org.ruoyi.chain.loader.MarkDownFileLoader 的能力迁移
 */
@Component
@AllArgsConstructor
@Slf4j
public class MarkDownFileLoader implements ResourceLoader {

    private final TextSplitter textSplitter;

    @Override
    public String getContent(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStreamReader reader = new InputStreamReader(inputStream);
             BufferedReader bufferedReader = new BufferedReader(reader)) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            log.error("读取 Markdown 文件失败", e);
        }
        return stringBuilder.toString();
    }

    @Override
    public List<String> getChunkList(String content, String kid) {
        return textSplitter.split(content, kid);
    }
}
