package com.vetti.common.ai.whisper;

import cn.hutool.json.JSONObject;
import okhttp3.*;
import org.apache.commons.io.FileUtils;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.concurrent.CountDownLatch;

public class RealtimeTranscriptionMicrophone {

    private static final String API_KEY = "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";
    private static final String URL = "wss://api.openai.com/v1/realtime?intent=transcription";
    private static final int SAMPLE_RATE = 16000; // 16kHz
    private static final int BUFFER_SIZE = 4096; // 4 KB 每次读取
    private static final int BITS_PER_SAMPLE = 16; // 每样本 16 位

    public static void main(String[] args) throws Exception {

        OkHttpClient client = new OkHttpClient();
        CountDownLatch latch = new CountDownLatch(1);

        // 设置 WebSocket 请求
        Request request = new Request.Builder()
                .url(URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("OpenAI-Beta", "realtime=v1")
                .build();

        WebSocket ws = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("✅ WebSocket 连接成功");

                //发送配置
                JSONObject config = new JSONObject();
                JSONObject sessionConfig = new JSONObject();
                JSONObject transcription = new JSONObject();
                JSONObject turnDetection = new JSONObject();

                // 配置转录参数
                transcription.put("model", "gpt-4o-mini-transcribe");
                transcription.put("language", "zh"); // 中文
                // 配置断句检测
                turnDetection.put("type", "server_vad");
                turnDetection.put("prefix_padding_ms", 300);
                turnDetection.put("silence_duration_ms", 10);
                // 组装完整配置
                sessionConfig.put("input_audio_transcription", transcription);
                sessionConfig.put("turn_detection", turnDetection);
                config.put("type", "transcription_session.update");
                config.put("session", sessionConfig);

                webSocket.send(config.toString());

                // 1. 启动音频缓冲
//                webSocket.send("{\"type\": \"input_audio_buffer.start\"}");

                // 2. 开始录音并实时发送
                new Thread(() -> {
                    try {
                        // 设置麦克风输入流
//                        AudioFormat format = new AudioFormat(SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
//                        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
//                        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
//                        line.open(format);
//                        line.start();
//
//                        byte[] buffer = new byte[BUFFER_SIZE];
//                        int bytesRead;
//                        while ((bytesRead = line.read(buffer, 0, buffer.length)) > 0) {
//                            // 将音频数据转换为 Base64 编码的字符串
//                            byte[] audioData = new byte[bytesRead];
//                            System.arraycopy(buffer, 0, audioData, 0, bytesRead);
//                            String base64Audio = Base64.getEncoder().encodeToString(audioData);
//                            String message = "{ \"type\": \"input_audio_buffer.append\", \"audio\": \"" + base64Audio + "\" }";
//                            webSocket.send(message);
//                        }
                        File outputFile = new File("/Users/wangxiangshun/Desktop/临时文件/110/output_pcm_audio1.pcm");  // 输出PCM格式文件
                        ByteBuffer byteBuffer = ByteBuffer.wrap(FileUtils.readFileToByteArray(outputFile));
                        byte[] bytes = new byte[byteBuffer.remaining()];
                        //从缓冲区中读取数据并存储到指定的字节数组中
                        byteBuffer.get(bytes);
                        String base64Audio = Base64.getEncoder().encodeToString(bytes);
                        String message = "{ \"type\": \"input_audio_buffer.append\", \"audio\": \"" + base64Audio + "\" }";
                        webSocket.send(message);
                        // 3. 提交音频并请求转录
//                        webSocket.send("{\"type\": \"input_audio_buffer.commit\"}");
//                        webSocket.send("{\"type\": \"response.create\"}");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).start();
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("📩 收到转录结果: " + text);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.err.println("❌ 连接失败: " + t.getMessage());
                latch.countDown();
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("⚠️ 连接即将关闭: " + reason);
                webSocket.close(1000, null);
                latch.countDown();
            }
        });

        // 等待 WebSocket 关闭
        latch.await();
    }
}

