package com.gameplatform.server.task;

import com.gameplatform.server.model.dto.device.DeviceStatusResponse;
import com.gameplatform.server.service.device.DeviceStatusCheckService;
import com.gameplatform.server.service.external.ScriptClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.Exceptions;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;

/**
 * 设备状态检查定时任务
 */
@Component
@Slf4j
public class DeviceStatusCheckTask {

    private final ScriptClient scriptClient;
    private final DeviceStatusCheckService deviceStatusCheckService;

    public DeviceStatusCheckTask(ScriptClient scriptClient, DeviceStatusCheckService deviceStatusCheckService) {
        this.scriptClient = scriptClient;
        this.deviceStatusCheckService = deviceStatusCheckService;
    }

    /**
     * 每分钟检查一次空闲设备，并更新相关链接任务状态
     */
//    @Scheduled(fixedRate = 60000) // 每60秒执行一次
    public void checkIdleDevicesAndUpdateTasks() {
        log.debug("开始定时检查空闲设备");
        
        try {
            // 1. 获取所有设备状态（增加超时与错误兜底）
            DeviceStatusResponse deviceStatus = scriptClient
                    .checkAvailableDeviceStatus()
                    .timeout(Duration.ofSeconds(5))
                    .onErrorResume(throwable -> {
                        Throwable root = Exceptions.unwrap(throwable);
                        if (root instanceof java.util.concurrent.TimeoutException) {
                            log.warn("获取所有设备状态超时，跳过本次检查");
                        } else if (root instanceof InterruptedException) {
                            Thread.currentThread().interrupt();
                            log.warn("获取所有设备状态被中断，跳过本次检查");
                        } else {
                            log.error("获取所有设备状态失败", root);
                        }
                        return Mono.empty();
                    })
                    .blockOptional()
                    .orElse(null);
            
            if (deviceStatus == null) {
                log.warn("获取设备状态失败，跳过本次检查");
                return;
            }
            
            List<String> availableDevices = deviceStatus.getAvailableDevices();
            if (availableDevices.isEmpty()) {
                log.debug("当前没有空闲设备");
                return;
            }
            
            log.debug("发现 {} 个空闲设备: {}", availableDevices.size(), availableDevices);
            
            // 2. 对每个空闲设备检查是否有相关的LOGGED_IN状态链接任务
            for (String deviceId : availableDevices) {
                try {
                    deviceStatusCheckService.checkDeviceStatusAndUpdateTasks(deviceId, "定时检查");
                } catch (Exception e) {
                    log.error("检查设备 {} 状态时发生异常", deviceId, e);
                    // 继续检查下一个设备，不因为一个设备出错而中断整个流程
                }
            }
            
        } catch (Exception e) {
            log.error("定时检查空闲设备时发生异常", e);
        }
        
        log.debug("定时检查空闲设备完成");
    }
}
