package com.vetti.web.service.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vetti.common.core.domain.dto.RealtimeClientSecretDto;
import com.vetti.web.service.ICommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
 * 共同 信息 服务实现类
 *
 * @author WangXiangShun
 * @since 2025-08-27
 */
@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

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

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

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

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

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

    /**
     * 获取openAi客户端临时Key
     * @return
     */
    @Override
    public RealtimeClientSecretDto getRealtimeClientSecret() {
        RealtimeClientSecretDto dto = new RealtimeClientSecretDto();
        try {
            // 1. 创建 HTTP 客户端
            HttpClient client = HttpClient.newBuilder()
                    .version(HttpClient.Version.HTTP_2)
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();

            // 2. 构建请求体（空 JSON 对象）
            Map<String,Object> params = new HashMap<>();
            Map<String, Object> bodyEntity = new HashMap<>();
            bodyEntity.put("model",MODEL);
            bodyEntity.put("prompt",prompt);
            bodyEntity.put("language",language);
            params.put("input_audio_transcription",bodyEntity);

            Map<String, Object> bodyEntityConfig = new HashMap<>();
            bodyEntityConfig.put("type","semantic_vad");
            bodyEntityConfig.put("eagerness","high");
            params.put("turn_detection",bodyEntityConfig);

//            Map<String, Object> bodyEntityStream = new HashMap<>();
//            bodyEntityStream.put("type","full");
//            params.put("streaming",bodyEntityStream);

            String requestBody = JSONUtil.toJsonStr(params);
            // 3. 构建 HTTP 请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiClientTokenUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey) // 核心认证头
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();
            // 4. 发送请求并获取响应
            HttpResponse<String> response = client.send(
                    request,
                    HttpResponse.BodyHandlers.ofString()
            );
            // 5. 处理响应
            if (response.statusCode() == 200) {
                // 解析响应为实体类
                System.out.println(JSONUtil.toJsonStr(response.body()));
                Map entity = JSONUtil.toBean(response.body(), Map.class);
                if(entity.get("client_secret") != null) {
                    Map data = (Map) entity.get("client_secret");
                    dto.setClientSecret(data.get("value").toString());
                    dto.setExpiresAt(Long.valueOf(data.get("expires_at").toString()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dto;
    }
}
