package com.usky.cdi.service.job;

import com.alibaba.fastjson.JSONObject;
import com.usky.cdi.service.config.Gb28181VideoProperties;
import com.usky.cdi.service.impl.VideoDataTransferService;
import com.usky.cdi.service.impl.VideoStreamPushService;
import com.usky.cdi.service.util.Gb28181VideoPlatformClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * GB28181 视频对接定时任务
 * <p>
 * 基于国标流媒体平台（WVP 等）HTTP API 拉取设备/通道目录，并通过 MQTT 上报至市适配平台。
 * SIP 参数与平台「国标级联」配置页一致。
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "gb28181.video", name = "enabled", havingValue = "true")
public class VideoDeviceSyncJob {

    private final VideoDataTransferService videoDataTransferService;
    private final VideoStreamPushService videoStreamPushService;
    private final Gb28181VideoPlatformClient platformClient;
    private final Gb28181VideoProperties properties;

    /**
     * 定时同步视频设备目录
     */
    @Scheduled(cron = "${gb28181.video.sync-cron:0 0/30 * * * ?}")
    public void scheduledVideoDeviceSync() {
        log.info("开始执行 GB28181 视频设备同步定时任务");
        try {
            videoDataTransferService.synchronizeVideoDevices();
        } catch (Exception e) {
            log.error("GB28181 视频设备同步定时任务失败：{}", e.getMessage(), e);
        }
    }

    /**
     * 定时推流：WVP 点播拉流 + MQTT 上报播放地址
     */
    @Scheduled(cron = "${gb28181.video.stream-push-cron:0 */5 * * * ?}")
    public void scheduledVideoStreamPush() {
        if (!properties.isStreamPushEnabled()) {
            return;
        }
        log.info("开始执行 GB28181 视频流推送定时任务");
        try {
            videoStreamPushService.maintainActiveStreams();
        } catch (Exception e) {
            log.error("GB28181 视频流推送定时任务失败：{}", e.getMessage(), e);
        }
    }

    /**
     * 检查国标配置（对应页面「检查配置」），可供 Controller 或运维手动调用
     */
    public JSONObject checkGb28181Configuration() {
        return platformClient.checkConfiguration();
    }
}
