package com.cmvr.edge.client.webrtc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

/**
 * 旧 WebRTC 音频桥接兼容类。
 *
 * <p>实时对讲链路已经切换为浏览器 WebSocket PCM 音频 + 机器人 gRPC 音频流。
 * 这里保留原有 public 方法签名，避免旧信令代码编译失败；不再创建 WebRTC native 对象，
 * 不再处理 WebRTC 音频，也不会保存调试录音文件。</p>
 */
public class WebRtcAudioBridge {

    private static final Logger log = LoggerFactory.getLogger(WebRtcAudioBridge.class);
    private static final String DISABLED_MESSAGE = "WebRTC audio bridge disabled; use websocket audio endpoint";

    private final Map<String, Consumer<String>> signalingSenders = new ConcurrentHashMap<>();

    public void createSession(String sessionId,
                              Consumer<byte[]> browserAudioConsumer,
                              Consumer<String> signalingSender) {
        if (sessionId == null || sessionId.trim().isEmpty()) {
            return;
        }
        if (signalingSender != null) {
            signalingSenders.put(sessionId, signalingSender);
        }
        log.warn("{}, sessionId={}", DISABLED_MESSAGE, sessionId);
    }

    public void handleOffer(String sessionId, String sdp) {
        sendDisabledError(sessionId);
    }

    public void addIceCandidate(String sessionId, String sdpMid, int sdpMLineIndex, String candidate) {
        sendDisabledError(sessionId);
    }

    public void pushRobotAudio(String sessionId, long timestampMs, byte[] pcm48kMono) {
        log.debug("{}, ignored robot audio, sessionId={}, bytes={}",
                DISABLED_MESSAGE, sessionId, pcm48kMono == null ? 0 : pcm48kMono.length);
    }

    public void closeSession(String sessionId) {
        if (sessionId != null) {
            signalingSenders.remove(sessionId);
        }
    }

    @PreDestroy
    public void destroy() {
        signalingSenders.clear();
    }

    private void sendDisabledError(String sessionId) {
        Consumer<String> sender = signalingSenders.get(sessionId);
        if (sender == null) {
            log.warn("{}, sessionId={}", DISABLED_MESSAGE, sessionId);
            return;
        }
        try {
            sender.accept("{\"type\":\"error\",\"message\":\"" + DISABLED_MESSAGE + "\"}");
        } catch (Exception e) {
            log.warn("send disabled WebRTC error failed, sessionId={}", sessionId, e);
        }
    }
}
