package com.vetti.socket.agents;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * ElevenLabs Agent 客户端端点 - 处理逻辑
 */
@Slf4j
public class ElevenLabsAgentEndpoint extends Endpoint {

    private Session session;

    private final Consumer<Object> onMessage;

    public ElevenLabsAgentEndpoint(Consumer<Object> onMessage) {
        this.onMessage = onMessage;
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        log.info("自动链接上了Agent");
        this.session = session;
        log.info("可以开始发送消息了");
        session.addMessageHandler(String.class, onMessage::accept);
        session.addMessageHandler(ByteBuffer.class, onMessage::accept);
    }

    public void sendText(String text) {
        log.info("Agent-开始发送文本消息: {}", text);
        log.info("Agent-发送文本的Session为: {}", session);
        if (session == null || !session.isOpen()) return;
        log.info("Agent-开始发送文本发送: {}", text);
        session.getAsyncRemote().sendText(text);
    }

    public void sendBinaryText(String text) {
        log.info("Agent-开始发送语音文本消息: {}", text);
        log.info("Agent-发送语音文本的Session为: {}", session);
        if (session == null || !session.isOpen()) return;
        log.info("Agent-开始发送语音文本发送: {}", text);
        session.getAsyncRemote().sendText(text);
    }

    public void sendBinary(ByteBuffer buffer) {
        if (session == null || !session.isOpen()) return;

        session.getAsyncRemote().sendBinary(buffer);
    }

    public void close() throws IOException {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }

    /**
     * 针对语音流发送的时候,如果什么都接收不到的时候,就直接进行提交
     */
    public void commit() {
        if (session == null || !session.isOpen()) return;
        try {
            log.info("Agent-开发发送提交拉");
            Map<String,String> map = new HashMap<>();
            map.put("type","input_audio_buffer.commit");
            session.getAsyncRemote().sendText(JSONUtil.toJsonStr(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

