package com.vetti.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.vetti.common.ai.gpt.ChatGPTClient;
import com.vetti.common.exception.ServiceException;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.common.utils.spring.SpringUtils;
import com.vetti.hotake.domain.vo.HotakeAiInterviewQuestionRecordVo;
import com.vetti.web.entity.dto.ConvAiTokenDto;
import com.vetti.web.entity.dto.HotakeAiInterviewScoringDto;
import com.vetti.web.entity.vo.ConvAiTokenRequestVo;
import com.vetti.web.entity.vo.HotakeAiInterviewScoringVo;
import com.vetti.web.service.IElevenLabsConvAiTokenClientService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ElevenLabs Agent 信息 服务实现类
 *
 * @author WangXiangShun
 * @since 2025-08-27
 */
@Slf4j
@Service
public class ElevenLabsConvAiTokenClientServiceImpl implements IElevenLabsConvAiTokenClientService {
    // ========== 配置项（替换为你的实际值） ==========
    // 从ElevenLabs控制台获取
    private static final String XI_API_KEY = "sk_dfe2b45e19bf8ad93a71d3a0faa61619a91e817df549d116";
    // 如：agent_9401kd09yfjnes2vddz1n29wev2t
    private static final String AGENT_ID = "agent_9401kd09yfjnes2vddz1n29wev2t";
    //请求地址
    private static final String TOKEN_API_URL = "https://api.elevenlabs.io/v1/convai/conversation/token?agent_id=agent_9401kd09yfjnes2vddz1n29wev2t";
    // JSON媒体类型
    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");

    // ===================== 核心：获取ConvAI Token =====================
    /**
     * 获取ConvAI对话Token
     * @return Token响应对象
     * @throws IOException 网络/接口异常
     */
    public ConvAiTokenDto getConvAiToken() {
        try {
            // 用户ID（可选，用于区分用户）
            Long userId = SecurityUtils.getUserId();
            // 1. 构造请求体
            ConvAiTokenRequestVo requestBody = new ConvAiTokenRequestVo();
            requestBody.setAgent_id(AGENT_ID);
            // 会话ID：不传则生成随机ID
            requestBody.setConversation_id(UUID.randomUUID().toString());
            // 用户ID（可选）
            requestBody.setUser_id(userId.toString());
            // 2. 构建HTTP请求
            Request request = new Request.Builder()
                    .url(TOKEN_API_URL)
                    // 核心鉴权：添加XI-API-KEY头
                    .addHeader("xi-api-key", XI_API_KEY)
                    .addHeader("Content-Type", "application/json")
                    .build();
            // 初始化OkHttp客户端（设置超时）
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
            // 3. 执行请求并解析响应
            try (Response response = client.newCall(request).execute()) {
                log.info("1-错误信息为:{}",JSONUtil.toJsonStr(response));
                // 检查响应状态
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "无错误信息";
                    log.info("2-错误信息为:{}",errorBody);
                    throw new IOException("Failed to obtain Token");
                }
                // 解析JSON响应为实体类
                String responseBody = response.body().string();
                log.info("3-获取令牌数据:{}", responseBody);
                return JSONUtil.toBean(responseBody, ConvAiTokenDto.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("Failed to obtain Token");
        }

    }

    /**
     *
     * @param scoringVo 岗位信息
     * @return
     */
    @Override
    public HotakeAiInterviewScoringDto getAiInterviewScoring(HotakeAiInterviewScoringVo scoringVo) {

        log.info("请求参数为：{}",JSONUtil.toJsonStr(scoringVo));
        List<Map> list = new ArrayList<>();
        //获取第一条数据记录
        Map<String, String> mapEntity = new HashMap<>();
        //更新问题记录
        mapEntity.put("role", "system");
        mapEntity.put("content", "You are a construction industry interview expert. Evaluate candidate responses and provide scores (1-5) and follow-up questions when needed. Always respond in JSON format.");
        list.add(mapEntity);

        if(CollectionUtil.isNotEmpty(scoringVo.getAiInterviewQuestionRecordVoList())){
            for(HotakeAiInterviewQuestionRecordVo interviewQuestionRecordVo : scoringVo.getAiInterviewQuestionRecordVoList()){
                Map<String, String> mapEntityUser = new HashMap<>();
                //更新问题记录
                mapEntityUser.put("role", interviewQuestionRecordVo.getUserType());
                mapEntityUser.put("content", interviewQuestionRecordVo.getContentText());
                list.add(mapEntityUser);
            }
        }
        String promptJson = JSONUtil.toJsonStr(list);
        ChatGPTClient gptClient = SpringUtils.getBean(ChatGPTClient.class);
        String resultMsg = gptClient.handleAiChat(promptJson, "PF");
        log.info("返回的结果为:{}",resultMsg);
        try {
            //开始解析返回结果
            Map mapResultData = JSONUtil.toBean(resultMsg,Map.class);
            //获取评分
            Object scoreStr = mapResultData.get("score");
            Object assessment = mapResultData.get("assessment");

            HotakeAiInterviewScoringDto scoringDto = new HotakeAiInterviewScoringDto();
            scoringDto.setScore(scoreStr+"");
            scoringDto.setAssessment(assessment+"");
            scoringDto.setContent(scoreStr +"\n"+assessment);
            return scoringDto;
        }catch (Exception e){
            e.printStackTrace();
            HotakeAiInterviewScoringDto scoringDto = new HotakeAiInterviewScoringDto();
            scoringDto.setScore(0+"");
            scoringDto.setAssessment("Skills need improvement");
            scoringDto.setContent(0 +"\n"+"Skills need improvement");
            return scoringDto;
        }

    }


}
