package com.aegis.camera.task;

import com.aegis.camera.domain.Camera;
import com.aegis.camera.service.ICameraService;
import com.aegis.camera.service.StreamSessionService;
import com.aegis.camera.service.ZLMediaKitService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 流清理定时任务
 * 定期检查并关闭空闲的视频流，释放 ZLMediaKit 资源
 *
 * @author aegis
 */
@Slf4j
@Component
public class StreamCleanupTask {

    @Autowired
    private StreamSessionService streamSessionService;

    @Autowired
    private ICameraService cameraService;

    @Autowired
    private ZLMediaKitService zlMediaKitService;

    /**
     * 最大空闲时间（毫秒），默认 30 分钟
     * 超过此时间的流将被自动关闭
     */
    private static final long MAX_IDLE_TIME_MS = 30 * 60 * 1000L;

    /**
     * 每 5 分钟执行一次清理任务
     */
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void cleanupIdleStreams() {
        try {
            List<Long> idleCameraIds = streamSessionService.getIdleStreams(MAX_IDLE_TIME_MS);

            if (!idleCameraIds.isEmpty()) {
                log.info("发现 {} 个空闲流，开始清理", idleCameraIds.size());

                int successCount = 0;
                int failCount = 0;

                for (Long cameraId : idleCameraIds) {
                    try {
                        Camera camera = cameraService.getById(cameraId);
                        if (camera != null) {
                            // 停止 ZLMediaKit 中的流
                            zlMediaKitService.stopStream(camera);
                            // 从会话管理中移除
                            streamSessionService.unregisterStream(cameraId);
                            successCount++;
                            log.debug("已清理空闲流，摄像头ID: {}, 编码: {}", cameraId, camera.getCameraCode());
                        } else {
                            // 摄像头已不存在，直接移除记录
                            streamSessionService.unregisterStream(cameraId);
                            log.warn("摄像头不存在，已移除流记录，摄像头ID: {}", cameraId);
                        }
                    } catch (Exception e) {
                        failCount++;
                        log.error("清理空闲流失败，摄像头ID: {}", cameraId, e);
                        // 即使失败也尝试移除记录，避免重复处理
                        streamSessionService.unregisterStream(cameraId);
                    }
                }

                log.info("空闲流清理完成，成功: {}, 失败: {}", successCount, failCount);
            } else {
                log.debug("未发现空闲流，当前活跃流数量: {}", streamSessionService.getActiveStreamCount());
            }
        } catch (Exception e) {
            log.error("执行空闲流清理任务时发生异常", e);
        }
    }
}