package com.haobang.schedule;

import com.haobang.interlocking.ProbeHeartbeatClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 探针心跳调度器
 * 定时向平台端发送心跳
 */
@Component
public class ProbeHeartbeatScheduler {

    private static final Logger logger = LoggerFactory.getLogger(ProbeHeartbeatScheduler.class);

    @Autowired
    private ProbeHeartbeatClient probeHeartbeatClient;

    /**
     * 定时发送心跳
     * 使用动态间隔（根据配置）
     * 默认每60秒发送一次
     */
    @Scheduled(fixedDelayString = "${probe.heartbeat.interval-ms:60000}", initialDelayString = "${probe.heartbeat.initial-delay-ms:5000}")
    public void sendHeartbeat() {
        if (!probeHeartbeatClient.isEnabled()) {
            logger.debug("探针心跳已禁用，跳过本次心跳");
            return;
        }
        
        try {
            boolean success = probeHeartbeatClient.sendHeartbeat();
            
            if (success) {
                logger.debug("探针心跳发送成功, collectId={}", probeHeartbeatClient.getCollectId());
            } else {
                logger.warn("探针心跳发送失败, collectId={}", probeHeartbeatClient.getCollectId());
            }
        } catch (Exception e) {
            logger.error("探针心跳发送异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 手动触发心跳发送
     * @return 是否成功
     */
    public boolean manualSendHeartbeat() {
        logger.info("手动触发探针心跳");
        return probeHeartbeatClient.sendHeartbeat();
    }
}
