package top.imwork.exercise;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

public class VirtualThreadFileProcessor {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("用法: java VirtualThreadFileProcessor <文件路径>");
            System.exit(1);
        }

        String filePath = args[0];
        Path path = Paths.get(filePath);

        try {
            // 读取文件内容
            String content = Files.readString(path);

            // 使用虚拟线程池处理章节拆分
            List<Chapter> chapters = splitChaptersWithVirtualThreads(content);

            // 输出结果
            System.out.println("总共拆分成 " + chapters.size() + " 个章节");

            // 保存章节到文件
            saveChaptersToFiles(chapters);

        } catch (IOException e) {
            System.err.println("读取文件出错: " + e.getMessage());
        }
    }

    /**
     * 使用虚拟线程拆分章节
     */
    private static List<Chapter> splitChaptersWithVirtualThreads(String content) throws IOException {
        // 定义章节分割模式（可根据实际文件格式调整）
        Pattern chapterPattern = Pattern.compile(
                "(?i)(第[一二三四五六七八九十零百千0-9]+章|第[0-9]+节|CHAPTER\\s+[0-9IVX]+)"
        );

        // 查找所有章节标题位置
        List<Integer> chapterStarts = new ArrayList<>();
        var matcher = chapterPattern.matcher(content);
        while (matcher.find()) {
            chapterStarts.add(matcher.start());
        }

        List<Chapter> chapters = new ArrayList<>();
        List<CompletableFuture<Chapter>> futures = new ArrayList<>();

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

            // 为每个章节创建虚拟线程任务
            for (int i = 0; i < chapterStarts.size(); i++) {
                int startIndex = chapterStarts.get(i);
                int endIndex = (i < chapterStarts.size() - 1)
                        ? chapterStarts.get(i + 1)
                        : content.length();
                int chapterNumber = i + 1;

                CompletableFuture<Chapter> future = CompletableFuture.supplyAsync(() -> {
                    try {
                        String chapterContent = content.substring(startIndex, endIndex).trim();
                        return new Chapter(chapterNumber, extractChapterTitle(chapterContent), chapterContent);
                    } catch (Exception e) {
                        System.err.println("处理章节 " + chapterNumber + " 时出错: " + e.getMessage());
                        return new Chapter(chapterNumber, "错误章节", "");
                    }
                }, executor);

                futures.add(future);
            }

            // 等待所有任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

            // 收集结果
            for (var future : futures) {
                chapters.add(future.join());
            }
        }

        return chapters;
    }

    /**
     * 提取章节标题
     */
    private static String extractChapterTitle(String content) {
        // 取前两行作为标题，或找到第一个换行符
        int firstNewline = content.indexOf('\n');
        if (firstNewline != -1) {
            String title = content.substring(0, Math.min(firstNewline, 100)).trim();
            return title.length() > 50 ? title.substring(0, 50) + "..." : title;
        }
        return content.length() > 50 ? content.substring(0, 50) + "..." : content;
    }

    /**
     * 保存章节到单独的文件
     */
    private static void saveChaptersToFiles(List<Chapter> chapters) {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<CompletableFuture<Void>> saveFutures = new ArrayList<>();

            for (Chapter chapter : chapters) {
                saveFutures.add(CompletableFuture.runAsync(() -> {
                    try {
                        String fileName = String.format("chapter_%03d.txt", chapter.getNumber());
                        Path outputPath = Paths.get("output", fileName);
                        Files.createDirectories(outputPath.getParent());
                        Files.writeString(outputPath, chapter.getContent());
                        System.out.println("已保存: " + fileName);
                    } catch (IOException e) {
                        System.err.println("保存章节 " + chapter.getNumber() + " 失败: " + e.getMessage());
                    }
                }, executor));
            }

            CompletableFuture.allOf(saveFutures.toArray(new CompletableFuture[0])).join();
        }
    }

    /**
     * 章节数据类
     */
    static class Chapter {
        private final int number;
        private final String title;
        private final String content;

        public Chapter(int number, String title, String content) {
            this.number = number;
            this.title = title;
            this.content = content;
        }

        public int getNumber() { return number; }
        public String getTitle() { return title; }
        public String getContent() { return content; }

        @Override
        public String toString() {
            return String.format("第%d章: %s (长度: %d 字符)",
                    number, title, content.length());
        }
    }
}