package com.yaoai.ai.providers.service.impl;

import com.yaoai.ai.core.model.ChatRequest;
import com.yaoai.ai.core.model.ChatResponse;
import com.yaoai.ai.core.service.LlmService;
import com.yaoai.ai.providers.config.ArkProperties;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Slf4j
@Service
public class ArkLlmService implements LlmService {

    private final ArkProperties properties;
    private final RestClient restClient;

    public ArkLlmService(ArkProperties properties) {
        this.properties = properties;
        this.restClient = RestClient.builder()
                .baseUrl(properties.getBaseUrl())
                .defaultHeader("Authorization", "Bearer " + properties.getApiKey())
                .defaultHeader("Content-Type", "application/json")
                .build();
    }

    @Override
    public String chat(ChatRequest request) {
        // 如果未指定 model，使用默认文本模型
        if (request.getModel() == null) {
            request.setModel(properties.getTextModel());
        }
        log.debug("ARK LLM call: model={}, messages={}", request.getModel(), request.getMessages().size());

        try {
            ChatResponse response = restClient.post()
                    .uri("/chat/completions")
                    .body(request)
                    .retrieve()
                    .body(ChatResponse.class);

            if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
                throw new BizException(ErrorCode.INTERNAL_ERROR, "AI 服务返回空结果");
            }
            String content = response.firstContent();
            log.debug("ARK LLM response: {} chars", content.length());
            return content;
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            log.error("ARK LLM call failed", e);
            throw new BizException(ErrorCode.INTERNAL_ERROR, "AI 服务调用失败: " + e.getMessage());
        }
    }

    @Override
    public String getModelId() {
        return properties.getTextModel();
    }

    @Override
    public String getModelName() {
        return "豆包 Pro 文本生成";
    }

    @Override
    public String getProvider() {
        return "volcengine";
    }
}
