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.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;

@Slf4j
@Service
@ConditionalOnProperty(name = "ai.local-stub.enabled", havingValue = "false", matchIfMissing = true)
public class ArkLlmService implements LlmService {

    private static final String ARK_API_KEY_HINT =
            "未配置火山方舟 API Key，请设置环境变量 VOLCENGINE_ARK_API_KEY，或在 application-local.yml 中配置 volcengine.ark.api-key";

    private final ArkProperties properties;
    private final RestClient restClient;

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

    @Override
    public String chat(ChatRequest request) {
        String apiKey = resolveApiKey();
        // 如果未指定 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")
                    .header("Authorization", "Bearer " + apiKey)
                    .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 (RestClientResponseException e) {
            if (e.getStatusCode().value() == 400 && request.getResponseFormat() != null) {
                log.warn("ARK LLM response_format not accepted, retrying without response_format: body={}",
                        e.getResponseBodyAsString());
                request.setResponseFormat(null);
                return chat(request);
            }
            if (e.getStatusCode().value() == 401) {
                throw new BizException(ErrorCode.INTERNAL_ERROR,
                        "AI 服务鉴权失败，请检查 VOLCENGINE_ARK_API_KEY 是否正确且仍有效");
            }
            log.error("ARK LLM call failed: status={}, body={}", e.getStatusCode(), e.getResponseBodyAsString(), e);
            throw new BizException(ErrorCode.INTERNAL_ERROR,
                    "AI 服务调用失败: HTTP " + e.getStatusCode().value());
        } 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";
    }

    private String resolveApiKey() {
        String apiKey = properties.getApiKey();
        if (apiKey == null || apiKey.isBlank()) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, ARK_API_KEY_HINT);
        }
        String normalized = apiKey.trim();
        if ("your-ark-api-key".equalsIgnoreCase(normalized) || "your_ark_api_key".equalsIgnoreCase(normalized)) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, ARK_API_KEY_HINT);
        }
        return normalized;
    }
}
