package top.r3944realms.docchecktoolrefactored.ui.task;

import javafx.concurrent.Task;
import lombok.extern.slf4j.Slf4j;
import top.r3944realms.docchecktoolrefactored.System;
import top.r3944realms.docchecktoolrefactored.ThreadPoolManager;
import top.r3944realms.docchecktoolrefactored.core.AddressFileGenerator;
import top.r3944realms.docchecktoolrefactored.core.LogicalAddressFileGenerator;
import top.r3944realms.docchecktoolrefactored.core.PhysicalAddressFileGenerator;
import top.r3944realms.docchecktoolrefactored.util.LoggerMarker;

import java.io.File;
import java.util.concurrent.*;

@Slf4j
public class AddressFileGenerationTask extends Task<String> {

    private final String sourcePath;
    private final File outputFile;
    private final int folderType;
    private final AddressFileGenerator generator;
    private ExecutorService executor;
    private Future<?> future;


    public AddressFileGenerationTask(String sourcePath,
                                     File outputFile,
                                     int folderType,
                                     boolean isLogic) {
        this.sourcePath = sourcePath;
        this.outputFile = outputFile;
        this.folderType = folderType;
        this.generator = isLogic ? new LogicalAddressFileGenerator() : new PhysicalAddressFileGenerator();
    }

    @Override
    protected String call() throws Exception {
        updateMessage("初始化生成任务...");
        generator.setProgressCallback(new AddressFileGenerator.ProgressCallback() {
            @Override
            public void onPhaseStarted(AddressFileGenerator.Phase phase) {
              switch (phase) {
                  case GENERATE_LOGICAL -> updateMessage("正在生成逻辑地址 CSV 文件 ...");
                  case GENERATE_PHYSICAL -> updateMessage("正在生成物理地址 CSV 文件 ...");
              }
            }

            @Override
            public void onPhaseProgress(AddressFileGenerator.Phase phase, int current, int total) {
              if (total > 0) {
                  updateProgress(current, total);
                  switch (phase) {
                      case GENERATE_LOGICAL -> updateMessage(String.format("在生成逻辑地址 CSV : %d/%d", current, total));
                      case GENERATE_PHYSICAL -> updateMessage(String.format("在生成物理地址 CSV : %d/%d", current, total));
                  }
              }
            }

            @Override
            public void onPhaseCompleted(AddressFileGenerator.Phase phase) {
              switch (phase) {
                  case GENERATE_LOGICAL -> updateMessage("已完成生成逻辑地址 CSV 文件任务");
                  case GENERATE_PHYSICAL -> updateMessage("已完成生成物理地址 CSV 文件任务");
              }
            }
        });
        executor = ThreadPoolManager.createPool("address-file-generate-pool", System.getAvailableProcessors());

        // 提交任务到线程池
        future = executor.submit(() -> {
            try {
                generator.generateAddressFile(sourcePath, outputFile, folderType);
            } catch (Exception e) {
                // 不包装已经格式化好的重复档号异常
                if (e instanceof RuntimeException &&
                        e.getMessage() != null &&
                        e.getMessage().startsWith("存在重复档号：")) {
                    outputFile.delete(); // 删除空内容的csv文件
                    throw e; // 直接抛出，保留原始消息
                }
                if (e instanceof RuntimeException &&
                        e.getMessage() != null &&
                        e.getMessage().startsWith("存在重复文件名：")) {
                    outputFile.delete();// 删除空内容的csv文件
                    throw e; // 直接抛出，保留原始消息
                }
                throw new RuntimeException("地址文件生成失败", e);
            }
        });

        try {
            // 等待执行完成或超时
            future.get(System.getSetting().getTaskTimeout(), TimeUnit.SECONDS);
            return outputFile.getAbsolutePath();

        } catch (TimeoutException e) {
            String errorMsg = "生成任务超时 (>" + System.getSetting().getTaskTimeout() + "s)";
            updateMessage(errorMsg);
            throw new RuntimeException(errorMsg, e);

        } catch (ExecutionException e) {
            String errorMsg = "生成任务失败: " + e.getCause().getMessage();
            updateMessage(errorMsg);
            throw new RuntimeException(errorMsg, e.getCause());

        } catch (InterruptedException e) {
            updateMessage("生成任务被取消");
            Thread.currentThread().interrupt();
            throw e;

        } finally {
            // 清理资源
            if (executor != null) {
                try {
                    executor.shutdown();
                    if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
                        executor.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    executor.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        log.info(LoggerMarker.DEBUG_MARKER, "生成任务已取消: {}", outputFile.getAbsolutePath());
        updateMessage("正在取消生成任务...");

        // 先取消 Future
        if (future != null && !future.isDone()) {
            future.cancel(true);
        }

        // 给任务一些时间响应中断
        try {
            if (executor != null) {
                executor.shutdown(); // 先尝试正常关闭
                if (!executor.awaitTermination(2, TimeUnit.SECONDS)) {
                    executor.shutdownNow(); // 强制关闭
                }
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }

        updateMessage("生成任务已取消");
    }
}
