package com.fuyuanshen.app.http;

import okhttp3.*;

import java.io.IOException;

public class OkHttpTtsClient {
    
    private OkHttpClient client = new OkHttpClient();
    private String accessKeyId;
    private String accessKeySecret;
    private String appKey;
    
    public OkHttpTtsClient(String accessKeyId, String accessKeySecret, String appKey) {
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.appKey = appKey;
    }
    
    /**
     * 使用OkHttp调用TTS服务
     */
    public byte[] synthesizeTextToMp3(String text) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        
        String jsonPayload = String.format(
            "{\"appkey\":\"%s\",\"text\":\"%s\",\"voice\":\"zhifeng\",\"format\":\"MP3\",\"sample_rate\":24000,\"volume\":50,\"speech_rate\":0,\"pitch_rate\":0}",
            appKey,
            text.replace("\"", "\\\"")
        );
        
        RequestBody body = RequestBody.create(JSON,jsonPayload);
        Request request = new Request.Builder()
            .url("https://nls-gateway.cn-shanghai.aliyuncs.com/v1/tts")
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", "Bearer " + getAccessToken())
            .build();
        
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("HTTP请求失败: " + response.code());
            }
            
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                return responseBody.bytes();
            } else {
                throw new IOException("响应体为空");
            }
        }
    }
    
    private String getAccessToken() {
        // 实现获取访问令牌的逻辑
        return "your-access-token";
    }
}
