package tech.easyflow.agent.runtime.hitl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tech.easyflow.agent.entity.AgentHitlPending;
import tech.easyflow.common.cache.DistributedScheduledLock;

import java.util.List;

/**
 * Agent 工具审批 pending 过期清理任务。
 */
@Component
public class AgentHitlPendingExpirationTask {

    private static final Logger LOG = LoggerFactory.getLogger(AgentHitlPendingExpirationTask.class);
    private static final int BATCH_SIZE = 100;

    private final AgentHitlPendingService pendingService;

    /**
     * 创建任务。
     *
     * @param pendingService pending 服务
     */
    public AgentHitlPendingExpirationTask(AgentHitlPendingService pendingService) {
        this.pendingService = pendingService;
    }

    /**
     * 定期将超时 pending 标记为 EXPIRED。
     */
    @Scheduled(fixedDelayString = "${easyflow.agent.runtime.hitl-expire-scan-delay:60000}", initialDelay = 60000L)
    @DistributedScheduledLock(key = "easyflow:schedule:agent-hitl:expire-pending", leaseSeconds = 300L)
    public void expirePending() {
        try {
            List<AgentHitlPending> expired = pendingService.expirePending(BATCH_SIZE);
            if (!expired.isEmpty()) {
                LOG.info("Expired Agent HITL pending records, count={}", expired.size());
            }
        } catch (RuntimeException e) {
            LOG.warn("Expire Agent HITL pending records failed, message={}", e.getMessage(), e);
        }
    }
}
