package com.easyagents.document.core.support;

import com.easyagents.document.core.DocumentParseService;
import com.easyagents.document.core.async.DocumentAsyncTaskManager;
import com.easyagents.document.core.async.DocumentAsyncTaskUpdater;
import com.easyagents.document.core.entity.ParseFile;
import com.easyagents.document.core.entity.ParseRequest;
import com.easyagents.document.core.entity.ParseResponse;
import com.easyagents.document.core.entity.ParseTaskInfo;
import com.easyagents.document.core.entity.ParseTaskStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * 带统一异步任务能力的文档解析服务基类。
 * 支持 ppt 和 excel，pdf 和 word 文档使用 mineru 自带异步能力
 *
 * @param <R> 请求类型
 * @author Codex
 * @since 2026-04-16
 */
public abstract class AbstractAsyncDocumentParseService<R extends ParseRequest> implements DocumentParseService<R> {

    private final DocumentAsyncTaskManager taskManager;

    /**
     * 创建服务基类。
     *
     * @param taskManager 异步任务管理器
     */
    protected AbstractAsyncDocumentParseService(DocumentAsyncTaskManager taskManager) {
        if (taskManager == null) {
            throw new IllegalArgumentException("DocumentAsyncTaskManager must not be null");
        }
        this.taskManager = taskManager;
    }

    @Override
    public ParseResponse parse(ParseRequest request) {
        return doParse(normalizeRequest(request), null);
    }

    @Override
    public ParseTaskStatus submit(ParseRequest request) {
        final R normalizedRequest = normalizeRequest(request);
        return taskManager.submit(
            normalizedRequest.getBackend(),
            collectFileNames(normalizedRequest),
            updater -> doParse(normalizedRequest, updater)
        );
    }

    @Override
    public ParseTaskStatus queryTask(String taskId) {
        return taskManager.queryTask(taskId);
    }

    @Override
    public ParseResponse queryResult(String taskId) {
        return taskManager.queryResult(taskId);
    }

    @Override
    public ParseTaskInfo queryTaskInfo(String taskId) {
        return taskManager.queryTaskInfo(taskId);
    }

    /**
     * 归一化请求。
     *
     * @param request 原始请求
     * @return 归一化结果
     */
    protected abstract R normalizeRequest(ParseRequest request);

    /**
     * 执行解析。
     *
     * @param request 归一化请求
     * @param updater 进度更新器；同步解析时可能为 {@code null}
     * @return 解析结果
     */
    protected abstract ParseResponse doParse(R request, DocumentAsyncTaskUpdater updater);

    private List<String> collectFileNames(ParseRequest request) {
        List<String> fileNames = new ArrayList<String>();
        if (request == null || request.getFiles() == null) {
            return fileNames;
        }
        for (ParseFile file : request.getFiles()) {
            if (file != null && file.getFileName() != null) {
                fileNames.add(file.getFileName());
            }
        }
        return fileNames;
    }
}
