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.ai.providers.config.ModelCapability;
import com.yaoai.ai.providers.config.PlatformModelConfigService;
import com.yaoai.ai.providers.config.ProviderRestClientFactory;
import com.yaoai.ai.providers.config.ResolvedModelConfig;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 API_KEY_HINT =
            "未配置文本模型 API Key，请在运营端模型配置中填写，或设置 VOLCENGINE_ARK_API_KEY";

    private final ArkProperties properties;
    private final PlatformModelConfigService platformModelConfigService;
    private final ProviderRestClientFactory restClientFactory;

    public ArkLlmService(ArkProperties properties) {
        this(properties, null, new ProviderRestClientFactory());
    }

    @Autowired
    public ArkLlmService(ArkProperties properties,
                         PlatformModelConfigService platformModelConfigService,
                         ProviderRestClientFactory restClientFactory) {
        this.properties = properties;
        this.platformModelConfigService = platformModelConfigService;
        this.restClientFactory = restClientFactory;
    }

    @Override
    public String chat(ChatRequest request) {
        ResolvedModelConfig config = resolveConfig();
        String apiKey = resolveApiKey(config);
        if (request.getModel() == null || request.getModel().isBlank()) {
            request.setModel(config.modelId());
        }
        log.debug("LLM call: provider={}, model={}, messages={}",
                config.provider(), request.getModel(), request.getMessages().size());

        try {
            ChatResponse response = restClientFactory.create(config).post()
                    .uri(config.endpoint())
                    .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("LLM response: {} chars", content.length());
            return content;
        } catch (RestClientResponseException e) {
            if (e.getStatusCode().value() == 400 && request.getResponseFormat() != null) {
                log.warn("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, "文本模型鉴权失败，请检查 API Key 是否有效");
            }
            log.error("LLM call failed: status={}, body={}", e.getStatusCode(), e.getResponseBodyAsString(), e);
            throw new BizException(ErrorCode.INTERNAL_ERROR,
                    "文本模型调用失败: HTTP " + e.getStatusCode().value());
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            log.error("LLM call failed", e);
            throw new BizException(ErrorCode.INTERNAL_ERROR, "文本模型调用失败: " + e.getMessage());
        }
    }

    @Override
    public String getModelId() {
        return resolveConfig().modelId();
    }

    @Override
    public String getModelName() {
        return resolveConfig().modelName();
    }

    @Override
    public String getProvider() {
        return resolveConfig().provider();
    }

    private ResolvedModelConfig resolveConfig() {
        if (platformModelConfigService != null) {
            return platformModelConfigService.resolve(ModelCapability.TEXT);
        }
        return new ResolvedModelConfig(
                "volcengine",
                "Volcengine ARK",
                "openai",
                properties.getBaseUrl(),
                properties.getApiKey(),
                properties.getTextModel(),
                "Doubao Text",
                "/chat/completions",
                null,
                null
        );
    }

    private String resolveApiKey(ResolvedModelConfig config) {
        String apiKey = config.apiKey();
        if (apiKey == null || apiKey.isBlank()) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, API_KEY_HINT);
        }
        String normalized = apiKey.trim();
        if ("your-ark-api-key".equalsIgnoreCase(normalized)
                || "your_ark_api_key".equalsIgnoreCase(normalized)
                || PlatformModelConfigService.MASKED_API_KEY.equals(normalized)) {
            throw new BizException(ErrorCode.INTERNAL_ERROR, API_KEY_HINT);
        }
        return normalized;
    }
}
