package com.lingyue.ai.client;

import com.lingyue.ai.dto.ChatMessage;
import com.lingyue.ai.dto.ChatRequest;
import com.lingyue.ai.dto.ChatResponse;
import com.lingyue.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;

/**
 * DeepSeek API 客户端
 *
 * @author lingyue
 * @since 2026-01-15
 */
@Slf4j
@Component
public class DeepSeekClient {

    private final WebClient webClient;
    private final String chatPath;

    private final String defaultModel;

    public DeepSeekClient(
            @Value("${bailian.deepseek.base-url}") String bailianApiUrl,
            @Value("${bailian.deepseek.api-key}") String bailianApiKey,
            @Value("${bailian.deepseek.model-name}") String bailianModel
    ) {
        String apiUrl = bailianApiUrl;
        String apiKey = bailianApiKey;
        this.defaultModel = bailianModel;
        this.chatPath = apiUrl != null && apiUrl.endsWith("/v1") ? "/chat/completions" : "/v1/chat/completions";
        this.webClient = WebClient.builder()
                .baseUrl(apiUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .build();
        log.info("DeepSeek 客户端初始化: baseUrl={}, model={}", apiUrl, defaultModel);
    }

    /**
     * 发送 Chat Completion 请求
     *
     * @param request 请求对象
     * @return 响应对象
     */
    public ChatResponse chat(ChatRequest request) {
        try {
            ChatResponse response = webClient
                    .post()
                    .uri(chatPath)
                    .bodyValue(request)
                    .retrieve()
                    .bodyToMono(ChatResponse.class)
                    .block();

            if (response == null) {
                throw new ServiceException("DeepSeek 返回空响应");
            }

            log.debug("DeepSeek 调用成功: model={}, tokens={}",
                    response.getModel(),
                    response.getUsage() != null ? response.getUsage().getTotal_tokens() : "N/A");

            return response;

        } catch (Exception e) {
            log.error("DeepSeek API 调用失败: {}", e.getMessage(), e);
            throw new ServiceException("AI 服务调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 简单文本生成
     *
     * @param prompt 提示词
     * @return 生成的文本
     */
    public String complete(String prompt) {
        ChatRequest request = ChatRequest.builder()
                .model(defaultModel)
                .messages(List.of(ChatMessage.user(prompt)))
                .build();

        ChatResponse response = chat(request);
        return response.getFirstContent();
    }

    /**
     * 带系统提示的文本生成
     *
     * @param systemPrompt 系统提示
     * @param userPrompt   用户提示
     * @return 生成的文本
     */
    public String complete(String systemPrompt, String userPrompt) {
        ChatRequest request = ChatRequest.builder()
                .model(defaultModel)
                .messages(List.of(
                        ChatMessage.system(systemPrompt),
                        ChatMessage.user(userPrompt)
                ))
                .build();

        ChatResponse response = chat(request);
        return response.getFirstContent();
    }

    /**
     * 多轮对话
     *
     * @param messages 消息列表
     * @return 生成的回复
     */
    public String chat(List<ChatMessage> messages) {
        ChatRequest request = ChatRequest.builder()
                .model(defaultModel)
                .messages(messages)
                .build();

        ChatResponse response = chat(request);
        return response.getFirstContent();
    }

}
