package com.ruoyi.common.config;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
public class AudioTextRequestClient {

    @Value("${audioText.asr}")
    private String asr;

    // 1. 读取 TTS 服务地址
    @Value("${audioText.tts}")
    private String tts;

    private final RestTemplate restTemplate = new RestTemplate();


    public String getTextFromAudioFile(MultipartFile file) throws IOException {
        HttpRequest request = HttpRequest.post(asr);
        request.header(HttpHeaders.CONTENT_TYPE,MediaType.MULTIPART_FORM_DATA_VALUE);
        request.form("file",file.getBytes(),file.getOriginalFilename());
        HttpResponse response = request.execute();
        if(response.isOk()){
            String body = response.body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if("0".equals(jsonObject.getString("code"))){
                return jsonObject.getString("text");
            }else{
                throw new RuntimeException("语音转文字接口调用失败: " + jsonObject.getString("error"));
            }
        }else{
            throw new RuntimeException("语音转文字接口调用失败: " + response.body());
        }
    }

    public byte[] getAudioInputStreamFromText(String audioText) throws UnsupportedEncodingException {
        JSONObject object = new JSONObject();
        object.put("text", audioText);
        object.put("speaker_id", 0);
        object.put("length_scale", 1.0);
        object.put("noise_scale", 0.667);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(object.toJSONString(), headers);
        ResponseEntity<byte[]> response = restTemplate.postForEntity(tts, entity, byte[].class);
        if (!response.getStatusCode().is2xxSuccessful()){
            String body = new String(response.getBody(),"UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(body);
            throw new RuntimeException("文字转语音接口调用失败: " + jsonObject.getString("error"));
        }else{
            return response.getBody();
        }
    }
}
