package com.easyagents.document.core.async;

import com.easyagents.document.core.entity.ParseResponse;
import com.easyagents.document.core.entity.ParseTaskInfo;
import com.easyagents.document.core.entity.ParseTaskStatus;

/**
 * 文档异步任务记录。
 *
 * @author Codex
 * @since 2026-04-16
 */
public class DocumentAsyncTaskRecord {

    private final ParseTaskStatus status;
    private ParseResponse result;

    /**
     * 创建任务记录。
     *
     * @param status 初始状态
     */
    public DocumentAsyncTaskRecord(ParseTaskStatus status) {
        this.status = status;
    }

    /**
     * 获取状态快照。
     *
     * @return 状态快照
     */
    public synchronized ParseTaskStatus getStatusSnapshot() {
        return copyStatus(status);
    }

    /**
     * 获取聚合信息快照。
     *
     * @return 聚合信息
     */
    public synchronized ParseTaskInfo getTaskInfoSnapshot() {
        ParseTaskInfo taskInfo = ParseTaskInfo.fromStatus(status);
        taskInfo.setResult(result);
        return taskInfo;
    }

    /**
     * 获取结果。
     *
     * @return 最终结果
     */
    public synchronized ParseResponse getResult() {
        return result;
    }

    /**
     * 更新任务状态。
     *
     * @param newStatus 新状态
     */
    public synchronized void updateStatus(ParseTaskStatus newStatus) {
        if (newStatus == null) {
            return;
        }
        copyInto(newStatus, status);
    }

    /**
     * 更新任务结果。
     *
     * @param result 最终结果
     */
    public synchronized void setResult(ParseResponse result) {
        this.result = result;
    }

    private ParseTaskStatus copyStatus(ParseTaskStatus source) {
        ParseTaskStatus copy = new ParseTaskStatus();
        copyInto(source, copy);
        return copy;
    }

    private void copyInto(ParseTaskStatus source, ParseTaskStatus target) {
        target.setTaskId(source.getTaskId());
        target.setStatus(source.getStatus());
        target.setBackend(source.getBackend());
        target.setFileNames(source.getFileNames());
        target.setCreatedAt(source.getCreatedAt());
        target.setStartedAt(source.getStartedAt());
        target.setCompletedAt(source.getCompletedAt());
        target.setError(source.getError());
        target.setStatusUrl(source.getStatusUrl());
        target.setResultUrl(source.getResultUrl());
        target.setQueuedAhead(source.getQueuedAhead());
        target.setProgressPercent(source.getProgressPercent());
        target.setCurrentStage(source.getCurrentStage());
        target.setProcessedItems(source.getProcessedItems());
        target.setTotalItems(source.getTotalItems());
        target.setStatusMessage(source.getStatusMessage());
    }
}
