package com.vetti.common.ai;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.json.JSONUtil;

public class WhisperTest {
    private static final String API_KEY = "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";
    private static final String AUDIO_PATH = "/Users/wangxiangshun/Public/project-aio/vetti/vetti-service/output.mp3"; // 替换为你的音频文件路径

    public static void main(String[] args) throws Exception {
        // 1. 检查音频文件是否存在
        if (!Files.exists(Paths.get(AUDIO_PATH))) {
            System.err.println("音频文件不存在: " + AUDIO_PATH);
            return;
        }

        // 2. 构建multipart/form-data请求（上传文件）
        MultipartBodyPublisher multipart = new MultipartBodyPublisher();
        multipart.addPart("model", "whisper-1");
        multipart.addFilePart("file", AUDIO_PATH);

        // 3. 发送请求
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.openai.com/v1/audio/transcriptions"))
                .header("Authorization", "Bearer " + API_KEY)
                .POST(multipart.build())
                .build();

        // 4. 获取并打印完整响应
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("状态码: " + response.statusCode());
        System.out.println("响应体: " + response.body());

        // 5. 解析结果（如果成功）
        if (response.statusCode() == 200) {

            System.out.println("识别结果: " + JSONUtil.toJsonStr(response.body()));
        }
    }
}

// 辅助类：处理multipart/form-data格式
class MultipartBodyPublisher {
    private final Map<String, String> parts = new HashMap<>();
    private String filePartName;
    private String filePath;

    public void addPart(String name, String value) {
        parts.put(name, value);
    }

    public void addFilePart(String name, String path) {
        this.filePartName = name;
        this.filePath = path;
    }

    public HttpRequest.BodyPublisher build() throws Exception {
        // 实际项目中建议使用成熟的HTTP客户端（如OkHttp）处理multipart，此处为简化示例
        // 完整实现需处理边界、文件流等，可参考：https://stackoverflow.com/a/65271748
        return HttpRequest.BodyPublishers.ofString(""); // 仅示例框架，需完善
    }
}
