package com.vetti.common.ai.whisper;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 语音转换文本
 */
@Component
public class WhisperClient {

    @Value("${whisper.apiUrl}")
    private String API_URL;

    @Value("${whisper.model}")
    private String MODEL;

    @Value("${whisper.apiKey}")
    private String apiKey;

    @Value("${whisper.language}")
    private String language;

    /**
     * 将音频文件转换为文本
     *
     * @param audioFile 音频文件
     * @param options   可选参数 (language, response_format等)
     * @return 转换后的文本
     * @throws IOException      网络或文件操作异常
     */
    private String transcribe(File audioFile, Map<String, String> options, OkHttpClient client) throws IOException {
        // 验证文件是否存在
        if (!audioFile.exists()) {
            throw new IllegalArgumentException("音频文件不存在: " + audioFile.getAbsolutePath());
        }
        // 构建请求体
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("model", MODEL)
                .addFormDataPart("file", audioFile.getName(),
                        RequestBody.create(audioFile, MediaType.parse("audio/opus")));
        // 添加可选参数
        if (options != null) {
            for (Map.Entry<String, String> entry : options.entrySet()) {
                bodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        // 构建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .header("Authorization", "Bearer " + apiKey)
                .post(bodyBuilder.build())
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            String responseBody = response.body().string();
            if (!response.isSuccessful()) {
                throw new RuntimeException(
                        "API请求失败: " + response.code() +
                                ", 详情: " + responseBody
                );
            }
            return responseBody;
        }
    }

    /**
     * 将音频文件转换为文本
     * @param bytes 语音流
     * @param fileName 文件名
     * @return
     * @throws Exception
     */
    public String transcribeAudio(byte[] bytes, String fileName) throws Exception {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        // 构建请求体，包含音频流
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("model", MODEL)
                .addFormDataPart(
                        "file",
                        fileName,
                        RequestBody.create(MediaType.parse("audio/opus"), bytes)
                )
                .addFormDataPart("response_format", "json")
                .build();
        Request request = new Request.Builder()
                .url(API_URL)
                .header("Authorization", "Bearer " + API_URL)
                .post(requestBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response: " + response);
            }
            return response.body().string();
        }
    }


    /**
     * 处理语音转换成文字
     *
     * @param audioFileUrl 要进行转换的语音逻辑
     * @return
     */
    public String handleVoiceToText(String audioFileUrl) {
        System.out.println("1-处理记录时间："+System.currentTimeMillis()/1000);
        String resultText = "";
        OkHttpClient client = new OkHttpClient();
        // 音频文件路径
        File audioFile = new File(audioFileUrl);
        try {
            // 添加可选参数，例如指定语言为中文
            Map<String, String> options = new HashMap<>();
            options.put("language", language);
            resultText = transcribe(audioFile, options, client);
            if(StrUtil.isNotEmpty(resultText)){
                Map<String, String> map = JSONUtil.toBean(resultText, Map.class);
                resultText = map.get("text");
            }
            System.out.println("转写结果: " + resultText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("2-处理记录时间："+System.currentTimeMillis()/1000);
        return resultText;
    }
}