/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.service.impl
 * @ClassName: DeepSeekServiceImpl
 * @Description: DeepSeek AI模型服务实现
 * @Author: 张志锋
 * @Date: 2025-11-05
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zhpb.gdyd_zhpb_zgf.context.ModelRequestContextHolder;
import com.zhpb.gdyd_zhpb_zgf.entity.mysql.ModelRequestLog;
import com.zhpb.gdyd_zhpb_zgf.service.AIModelService;
import com.zhpb.gdyd_zhpb_zgf.service.ModelRequestLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpStatusCodeException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * DeepSeek AI模型服务实现
 */
@Service
public class DeepSeekServiceImpl implements AIModelService {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekServiceImpl.class);

    @Value("${deepseek.api-key}")
    private String apiKey;

    @Value("${deepseek.api-url}")
    private String apiUrl;

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

    @Value("${deepseek.temperature:0.7}")
    private double temperature;

    // max_tokens不再限制，让模型自由决定输出长度

    private final RestTemplate restTemplate;
    private final ModelRequestLogService modelRequestLogService;

    /**
     * 创建带超时配置的RestTemplate
     */
    private static RestTemplate createRestTemplateWithTimeout() {
        org.springframework.http.client.SimpleClientHttpRequestFactory factory = 
            new org.springframework.http.client.SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(30000);  // 连接超时30秒
        factory.setReadTimeout(180000);    // 读取超时180秒（AI模型响应可能较慢，特别是QwQ推理模型）
        return new RestTemplate(factory);
    }

    public DeepSeekServiceImpl(ModelRequestLogService modelRequestLogService) {
        this.restTemplate = createRestTemplateWithTimeout();
        this.modelRequestLogService = modelRequestLogService;
    }

    @Override
    public String generateResponse(String systemPrompt, String userMessage) {
        return generateResponse(systemPrompt, userMessage, false);
    }

    @Override
    public String generateResponse(String systemPrompt, String userMessage, boolean stream) {
        long startTime = System.currentTimeMillis();
        String requestJson = null;
        String responseBody = null;
        boolean success = false;
        String errorMessage = null;
        Integer promptTokens = null;
        Integer completionTokens = null;
        Integer totalTokens = null;
        try {
            logger.info("调用DeepSeek API - 模型: {}, 系统提示长度: {}, 用户消息长度: {}",
                       model, systemPrompt.length(), userMessage.length());

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("temperature", temperature);
            // 不设置max_tokens限制，让模型自由决定输出长度
            requestBody.put("stream", stream);

            // 构建消息
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", systemPrompt);

            Map<String, String> userMessageMap = new HashMap<>();
            userMessageMap.put("role", "user");
            userMessageMap.put("content", userMessage);

            requestBody.put("messages", Arrays.asList(systemMessage, userMessageMap));
            requestJson = JSON.toJSONString(requestBody);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送请求
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                apiUrl, HttpMethod.POST, requestEntity, String.class);

            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                responseBody = responseEntity.getBody();
                JSONObject jsonResponse = JSON.parseObject(responseBody);

                // 提取回复内容
                String content = jsonResponse.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");

                JSONObject usage = jsonResponse.getJSONObject("usage");
                if (usage != null) {
                    promptTokens = usage.getInteger("prompt_tokens");
                    completionTokens = usage.getInteger("completion_tokens");
                    totalTokens = usage.getInteger("total_tokens");
                }

                success = true;
                logger.info("DeepSeek API调用成功，响应长度: {}", content.length());
                return content;
            } else {
                logger.error("DeepSeek API调用失败，状态码: {}", responseEntity.getStatusCode());
                throw new RuntimeException("DeepSeek API调用失败: " + responseEntity.getStatusCode());
            }

        } catch (HttpStatusCodeException e) {
            responseBody = e.getResponseBodyAsString();
            errorMessage = e.getMessage();
            logger.error("调用DeepSeek API异常: {}", e.getMessage());
            throw new RuntimeException("调用AI模型失败: " + e.getMessage(), e);
        } catch (Exception e) {
            errorMessage = e.getMessage();
            logger.error("调用DeepSeek API异常", e);
            throw new RuntimeException("调用AI模型失败: " + e.getMessage(), e);
        } finally {
            ModelRequestLog logEntry = new ModelRequestLog();
            logEntry.setRequestSource(ModelRequestContextHolder.getRequestSourceOrDefault("AI_PUBLIC"));
            logEntry.setRequestUrl(apiUrl);
            logEntry.setRequestMethod("POST");
            logEntry.setModelName(model);
            logEntry.setApiKey(apiKey);
            logEntry.setRequestPayload(requestJson);
            logEntry.setResponsePayload(responseBody);
            logEntry.setStatus(success ? "SUCCESS" : "FAILED");
            logEntry.setDurationMs(System.currentTimeMillis() - startTime);
            logEntry.setPromptTokens(promptTokens);
            logEntry.setCompletionTokens(completionTokens);
            logEntry.setTotalTokens(totalTokens);
            logEntry.setErrorMessage(errorMessage);
            modelRequestLogService.record(logEntry);
            ModelRequestContextHolder.clear();
        }
    }
}
