package tech.easyflow.ai.easyagentsflow.upload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * Public Workflow API 临时上传兜底清理任务。
 */
@Component
public class WorkflowApiUploadCleanupScheduler {

    private static final Logger LOG = LoggerFactory.getLogger(
            WorkflowApiUploadCleanupScheduler.class);
    private static final int CLEANUP_BATCH_SIZE = 100;
    private static final int CLEANUP_MAX_RECORDS_PER_RUN = 2_000;
    private static final Duration CLEANUP_TIME_BUDGET =
            Duration.ofSeconds(30);

    private final WorkflowApiUploadLifecycleService lifecycleService;

    /**
     * 创建临时上传清理任务。
     *
     * @param lifecycleService 临时上传生命周期服务
     */
    public WorkflowApiUploadCleanupScheduler(
            WorkflowApiUploadLifecycleService lifecycleService) {
        this.lifecycleService = lifecycleService;
    }

    /**
     * 定期清理终态、启动失败或状态已丢失的临时上传。
     */
    @Scheduled(
            fixedDelayString =
                    "${easyflow.workflow.api-upload.cleanup-interval:1m}")
    public void cleanup() {
        try {
            int processed = 0;
            long deadline = System.nanoTime()
                    + CLEANUP_TIME_BUDGET.toNanos();
            while (processed < CLEANUP_MAX_RECORDS_PER_RUN
                    && System.nanoTime() < deadline) {
                int batchSize = Math.min(
                        CLEANUP_BATCH_SIZE,
                        CLEANUP_MAX_RECORDS_PER_RUN - processed);
                int batchProcessed =
                        lifecycleService.cleanupExpired(batchSize);
                processed += batchProcessed;
                if (batchProcessed < batchSize) {
                    break;
                }
            }
            if (processed > 0) {
                LOG.info(
                        "已处理 {} 条工作流 API 临时上传清理记录",
                        processed);
            }
        } catch (RuntimeException error) {
            LOG.error("工作流 API 临时上传定时清理失败", error);
        }
    }
}
