package org.dromara.talk.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dromara.talk.service.ITtsService;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
@Component
public class TtsWebSocketHandler extends TextWebSocketHandler {

    private final ITtsService ttsService;

    public TtsWebSocketHandler(ITtsService ttsService) {
        this.ttsService = ttsService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("TTS WebSocket连接建立: {}", session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            JSONObject request = JSON.parseObject(message.getPayload());
            String text = request.getString("text");

            if (text == null || text.trim().isEmpty()) {
                sendError(session, -1, "文本内容不能为空");
                return;
            }

            ttsService.synthesize(text, null, new ITtsService.AudioCallback() {
                @Override
                public void onAudio(String base64Audio, int status) {
                    try {
                        JSONObject response = new JSONObject();
                        response.put("code", 0);
                        response.put("audio", base64Audio);
                        response.put("status", status);

                        session.sendMessage(new TextMessage(response.toJSONString()));
                    } catch (Exception e) {
                        log.error("发送音频数据失败", e);
                    }
                }

                @Override
                public void onError(int code, String msg) {
                    sendError(session, code, msg);
                }
            });

        } catch (Exception e) {
            log.error("处理TTS请求失败", e);
            sendError(session, -1, "处理请求失败: " + e.getMessage());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("TTS WebSocket连接关闭: {}, 状态: {}", session.getId(), status);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("TTS WebSocket传输错误: {}", session.getId(), exception);
    }

    private void sendError(WebSocketSession session, int code, String message) {
        try {
            JSONObject response = new JSONObject();
            response.put("code", code);
            response.put("message", message);

            session.sendMessage(new TextMessage(response.toJSONString()));
        } catch (Exception e) {
            log.error("发送错误消息失败", e);
        }
    }
}
