package org.dromara.ai.config;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.ai.provider.AiProviderManager;
import org.dromara.ai.provider.AzureOpenAiProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "ruoyi.ai.external-ai.azure", name = "enabled", havingValue = "true")
public class AzureOpenAiProviderConfig {

    private final AiProviderManager providerManager;

    @Value("${ruoyi.ai.external-ai.azure.api-key:}")
    private String apiKey;
    @Value("${ruoyi.ai.external-ai.azure.endpoint:}")
    private String endpoint;
    @Value("${ruoyi.ai.external-ai.azure.deployment-name:}")
    private String deploymentName;
    @Value("${ruoyi.ai.external-ai.azure.api-version:2023-12-01-preview}")
    private String apiVersion;
    @Value("${ruoyi.ai.providers.azure-openai.supported-models[0]:gpt-35-turbo}")
    private String supportedModel0;
    @Value("${ruoyi.ai.providers.azure-openai.supported-models[1]:gpt-4}")
    private String supportedModel1;
    @Value("${ruoyi.ai.providers.azure-openai.default-model:gpt-35-turbo}")
    private String defaultModel;
    @Value("${ruoyi.ai.external-ai.openai.timeout:60s}")
    private String timeout;

    @PostConstruct
    public void register() {
        if (apiKey == null || apiKey.isBlank() || endpoint == null || endpoint.isBlank() || deploymentName == null || deploymentName.isBlank()) {
            log.warn("Azure OpenAI 配置不完整，Provider 不注册");
            return;
        }
        AzureOpenAiProvider provider = new AzureOpenAiProvider();
        Map<String, Object> cfg = new HashMap<>();
        cfg.put("api-key", apiKey);
        cfg.put("endpoint", endpoint);
        cfg.put("deployment-name", deploymentName);
        cfg.put("api-version", apiVersion);
        cfg.put("default-model", defaultModel);
        cfg.put("timeout-ms", parseTimeoutMs(timeout));
        cfg.put("supported-models", List.of(supportedModel0, supportedModel1));
        provider.initialize(cfg);
        providerManager.registerProvider(provider);
        log.info("Azure OpenAI Provider 已注册");
    }

    private int parseTimeoutMs(String t) {
        try {
            if (t == null || t.isBlank()) return 60000;
            if (t.endsWith("ms")) return Integer.parseInt(t.substring(0, t.length() - 2));
            if (t.endsWith("s")) return Integer.parseInt(t.substring(0, t.length() - 1)) * 1000;
            if (t.endsWith("m")) return Integer.parseInt(t.substring(0, t.length() - 1)) * 60_000;
            return Integer.parseInt(t);
        } catch (Exception e) {
            return 60000;
        }
    }
}
