package com.yinlihupo.enlish.service.utils;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.openai.OpenAiAudioSpeechModel;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
@Slf4j
public class TTSUtil {

    private final OpenAiAudioSpeechModel speechModel;

    public TTSUtil(OpenAiAudioSpeechModel speechModel) {
        this.speechModel = speechModel;
    }

    /**
     * 生成语音并将二进制流写入 HTTP 响应
     *
     * @param text     需要转换的文本
     * @param response HTTP 响应对象
     */
    public void generateWordVoice(String text, HttpServletResponse response) {
        // 1. 参数校验
        if (!StringUtils.hasText(text)) {
            sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Input text cannot be empty");
            return;
        }

        try {
            // 3. 调用 OpenAI 接口获取音频数据
            byte[] audioBytes = speechModel.call(text);

            // 4. 设置 HTTP 响应头
            response.setContentType("audio/mpeg");
            response.setContentLength(audioBytes.length);

            // 可选：如果不希望浏览器自动播放，而是强制下载，请取消下面这行的注释
            // response.setHeader("Content-Disposition", "attachment; filename=\"speech.mp3\"");

            // 5. 将音频数据写入响应流
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                outputStream.write(audioBytes);
                outputStream.flush();
            }

        } catch (Exception e) {
            log.error("TTS Generation failed: {}", e.getMessage());
            sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "TTS Generation failed: " + e.getMessage());
        }
    }

    // 辅助方法：发送错误响应
    private void sendError(HttpServletResponse response, int status, String message) {
        try {
            response.sendError(status, message);
        } catch (IOException e) {
            // 忽略这里的错误，因为响应可能已经提交
        }
    }
}
