package com.kexue.skills.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kexue.skills.common.util.HttpUtil;
import com.kexue.skills.config.DeepSeekConfig;
import com.kexue.skills.entity.request.SkillAnalyzeRequest;
import com.kexue.skills.entity.request.SkillGenRequest;
import com.kexue.skills.entity.request.SkillRequest;
import com.kexue.skills.entity.response.SkillResponse;
import com.kexue.skills.service.SkillGenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 技能生成服务实现
 *
 * @author 维哥
 * @since 2026-01-28
 */
@Slf4j
@Service
public class SkillGenServiceImpl implements SkillGenService {

    @Autowired
    private DeepSeekConfig deepSeekConfig;

    /**
     * 生成技能
     *
     * @param request 生成请求
     * @return 生成结果
     */
    @Override
    public SkillResponse generateSkill(SkillGenRequest request) {
        log.info("生成技能请求: {}", request);
        String url = deepSeekConfig.getBaseUrl() + "/v1/chat/completions";
        SkillRequest skillRequest = new SkillRequest(true, deepSeekConfig.getChat().getModel(), 
                deepSeekConfig.getChat().getTemperature(), deepSeekConfig.getChat().getMaxTokens(),request.getPrompt());

        try {
            // 发送HTTP请求到deepseek API
            String deepseekResponse = HttpUtil.sendPostRequest(url, skillRequest, deepSeekConfig.getApiKey(), null);
            log.info("Deepseek API响应: {}", deepseekResponse);

            // 解析deepseek返回结果
            JSONObject responseJson = JSON.parseObject(deepseekResponse);
            List<JSONObject> choices = responseJson.getJSONArray("choices").toJavaList(JSONObject.class);
            
            if (choices != null && !choices.isEmpty()) {
                // 获取最新的choice（这里是第一个，因为只有一个）
                JSONObject latestChoice = choices.get(0);
                JSONObject message = latestChoice.getJSONObject("message");
                String content = message.getString("content");
                
                // 解析content中的JSON
                JSONObject skillJson = JSON.parseObject(content);
                SkillResponse skillResponse = new SkillResponse();
                skillResponse.setName(skillJson.getString("name"));
                skillResponse.setDescription(skillJson.getString("description"));
                skillResponse.setTags(skillJson.getJSONArray("tags").toJavaList(String.class));
                
                log.info("解析技能响应: {}", skillResponse);
                return skillResponse;
            }
        } catch (Exception e) {
            log.error("调用Deepseek API失败: {}", e.getMessage(), e);
        }

        return null;
    }



    /**
     * 分析技能
     *
     * @param request 分析请求
     * @return 分析结果
     */
    @Override
    public String analyzeSkill(SkillAnalyzeRequest request) {
        log.info("分析技能请求: {}", request);
        // 这里可以实现技能分析逻辑
        // 不需要数据库操作，直接返回结果
        return "技能分析成功: " + request.getSkillId();
    }
}
