package com.dora.scheduler;

import com.dora.service.RunningHubQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * RunningHub等待队列处理器
 * 定期检查等待队列，当有空位时提交新任务
 *
 * @author 1818AI
 * @since 2025-10-20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RunningHubQueueProcessor {

    private final RunningHubQueueService runningHubQueueService;

    @Value("${ai.providers.runninghub.max-polling-tasks:100}")
    private int maxPollingTasks;

    /**
     * 每5秒检查一次等待队列
     * 如果轮询任务数未满且队列中有任务，则提交新任务
     */
    @Scheduled(fixedDelayString = "${ai.providers.runninghub.queue-check-interval:5000}")
    public void processWaitingQueue() {
        try {
            int pollingCount = runningHubQueueService.getPollingTaskCount();
            int waitingCount = runningHubQueueService.getWaitingQueueSize();

            // 只有当队列不为空且有空位时才处理
            if (waitingCount > 0 && pollingCount < maxPollingTasks) {
                log.info("RunningHub队列处理器启动 - 正在轮询: {}/{}, 等待队列: {}", 
                         pollingCount, maxPollingTasks, waitingCount);
                
                int submitted = runningHubQueueService.processWaitingQueue();
                
                if (submitted > 0) {
                    log.info("RunningHub队列处理器完成 - 提交了{}个任务，当前轮询: {}/{}, 剩余队列: {}", 
                             submitted, 
                             runningHubQueueService.getPollingTaskCount(), 
                             maxPollingTasks,
                             runningHubQueueService.getWaitingQueueSize());
                }
            } else if (waitingCount > 0) {
                log.debug("RunningHub等待队列有{}个任务，但轮询已满({}/{})", 
                          waitingCount, pollingCount, maxPollingTasks);
            }
        } catch (Exception e) {
            log.error("RunningHub队列处理器执行失败", e);
        }
    }

    /**
     * 每分钟记录一次队列状态
     */
    @Scheduled(fixedDelay = 60000)
    public void logQueueStatus() {
        int pollingCount = runningHubQueueService.getPollingTaskCount();
        int waitingCount = runningHubQueueService.getWaitingQueueSize();
        
        if (pollingCount > 0 || waitingCount > 0) {
            log.info("RunningHub队列状态 - 正在轮询: {}/{}, 等待队列: {}", 
                     pollingCount, maxPollingTasks, waitingCount);
        }
    }
}


