package top.tqx.demo_1.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class SseEmitterManager {

    private final Map<String, SseEmitter> activeEmitters = new ConcurrentHashMap<>();

    public void register(String sessionId, SseEmitter emitter) {
        if (sessionId == null || emitter == null) {
            return;
        }
        unregister(sessionId);
        activeEmitters.put(sessionId, emitter);
        log.info("📝 SSEEmitter registered: sessionId={}, activeCount={}", sessionId, activeEmitters.size());
    }

    public void unregister(String sessionId) {
        if (sessionId == null) {
            return;
        }
        SseEmitter removed = activeEmitters.remove(sessionId);
        if (removed != null) {
            log.info("📝 SSEEmitter unregistered: sessionId={}, activeCount={}", sessionId, activeEmitters.size());
        }
    }

    public boolean stop(String sessionId) {
        if (sessionId == null) {
            return false;
        }

        SseEmitter emitter = activeEmitters.get(sessionId);
        if (emitter == null) {
            log.warn("⚠️ SSEEmitter not found for stop: sessionId={}", sessionId);
            return false;
        }

        try {
            emitter.send(SseEmitter.event()
                    .name("stop")
                    .data("{\"type\":\"stopped\",\"message\":\"用户主动中断\"}"));
            emitter.complete();
            activeEmitters.remove(sessionId);
            log.info("✅ SSEEmitter stopped: sessionId={}", sessionId);
            return true;
        } catch (Exception e) {
            log.error("❌ Failed to stop SSEEmitter: sessionId={}, error={}", sessionId, e.getMessage());
            activeEmitters.remove(sessionId);
            return false;
        }
    }

    public SseEmitter get(String sessionId) {
        return sessionId != null ? activeEmitters.get(sessionId) : null;
    }

    public boolean isActive(String sessionId) {
        return sessionId != null && activeEmitters.containsKey(sessionId);
    }

    public int getActiveCount() {
        return activeEmitters.size();
    }
}
