package com.ttstd.signaling.manager;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
 * 信令流量与连接指标采集器（进程内计数）。
 * 由 {@link com.ttstd.signaling.handler.SignalWebSocketHandler} 在关键事件处累加。
 */
@Component
public class SignalMetrics {
    private final AtomicLong totalMessages = new AtomicLong(0);
    private final AtomicLong totalOffers = new AtomicLong(0);
    private final AtomicLong totalAnswers = new AtomicLong(0);
    private final AtomicLong totalRejected = new AtomicLong(0);
    private final AtomicLong totalRegistered = new AtomicLong(0);
    private final AtomicLong peakSessions = new AtomicLong(0);
    public void incMessage() {
        totalMessages.incrementAndGet();
    }
    public void incOffer() {
        totalOffers.incrementAndGet();
    }
    public void incAnswer() {
        totalAnswers.incrementAndGet();
    }
    public void incRejected() {
        totalRejected.incrementAndGet();
    }
    public void incRegistered() {
        totalRegistered.incrementAndGet();
    }
    /** 记录历史峰值在线会话数（无锁 CAS 更新）。 */
    public void recordSessionCount(long count) {
        long cur;
        while ((cur = peakSessions.get()) < count) {
            if (peakSessions.compareAndSet(cur, count)) {
                break;
            }
        }
    }
    public Map<String, Object> snapshot() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("totalMessages", totalMessages.get());
        map.put("totalOffers", totalOffers.get());
        map.put("totalAnswers", totalAnswers.get());
        map.put("totalRejected", totalRejected.get());
        map.put("totalRegistered", totalRegistered.get());
        map.put("peakSessions", peakSessions.get());
        return map;
    }
}