package top.imwork.exercise;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

public class ChapterSplitter {

    /**
     * 使用虚拟线程处理章节分割的高级方法
     */
    public List<String> splitChapters(String content, Pattern delimiterPattern) {
        ConcurrentLinkedQueue<String> chapters = new ConcurrentLinkedQueue<>();

        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {

            // 找到所有分隔符位置
            var matcher = delimiterPattern.matcher(content);
            List<Integer> positions = matcher.results()
                    .map(match -> match.start())
                    .toList();

            // 创建并提交所有处理任务
            for (int i = 0; i < positions.size(); i++) {
                final int index = i;
                executor.submit(() -> {
                    int start = positions.get(index);
                    int end = (index < positions.size() - 1)
                            ? positions.get(index + 1)
                            : content.length();

                    String chapter = content.substring(start, end).trim();
                    chapters.add(chapter);

                    // 处理进度提示
                    if (chapters.size() % 10 == 0) {
                        System.out.println(Thread.currentThread() +
                                " 已处理 " + chapters.size() + " 个章节");
                    }
                });
            }
        }

        return chapters.stream().toList();
    }

    /**
     * 预定义的章节分割模式
     */
    public static Pattern getChineseChapterPattern() {
        return Pattern.compile("第[一二三四五六七八九十零百千万0-9]+章\\s*[：:】]?\\s*.+");
    }

    public static Pattern getEnglishChapterPattern() {
        return Pattern.compile("CHAPTER\\s+[0-9IVXL]+\\s*[:-]?\\s*.+", Pattern.CASE_INSENSITIVE);
    }

    public static Pattern getNumberChapterPattern() {
        return Pattern.compile("^\\d+\\.[\\s\\u3000].+", Pattern.MULTILINE);
    }
}