package com.agent.management.service;

import com.agent.management.model.vo.TranslationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * SSE 推送服务
 * 管理所有活跃的 SSE 连接，提供翻译结果推送能力
 */
@Slf4j
@Service
public class SseService {

    private static final int MAX_EMITTERS = 50;

    private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    /**
     * 创建新的 SSE 连接
     */
    public SseEmitter createEmitter() {
        if (emitters.size() >= MAX_EMITTERS) {
            throw new com.agent.management.common.exception.BusinessException(503, "SSE 连接数已满，请稍后重试");
        }
        // 5 分钟超时
        SseEmitter emitter = new SseEmitter(300_000L);
        emitters.add(emitter);

        emitter.onCompletion(() -> {
            emitters.remove(emitter);
            log.debug("[SSE] 连接完成, 当前连接数: {}", emitters.size());
        });
        emitter.onTimeout(() -> {
            emitters.remove(emitter);
            log.debug("[SSE] 连接超时, 当前连接数: {}", emitters.size());
        });
        emitter.onError(e -> {
            emitters.remove(emitter);
            log.debug("[SSE] 连接错误, 当前连接数: {}", emitters.size());
        });

        log.info("[SSE] 新连接建立, 当前连接数: {}", emitters.size());
        return emitter;
    }

    /**
     * 向所有连接推送翻译结果
     */
    public void pushTranslation(TranslationVO vo) {
        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(SseEmitter.event()
                        .name("translation")
                        .data(vo));
            } catch (IOException e) {
                emitters.remove(emitter);
            }
        }
        log.info("[SSE] 推送翻译结果: folderName={}, 当前连接数: {}", vo.getFolderName(), emitters.size());
    }
}
