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.OpenAiProvider;
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.openai", name = "enabled", havingValue = "true")
public class OpenAiProviderConfig {

    private final AiProviderManager providerManager;

    @Value("${ruoyi.ai.external-ai.openai.api-key:}")
    private String apiKey;

    @Value("${ruoyi.ai.external-ai.openai.base-url:https://api.openai.com}")
    private String baseUrl;

    @Value("${ruoyi.ai.external-ai.openai.default-model:gpt-3.5-turbo}")
    private String defaultModel;

    @Value("${ruoyi.ai.providers.openai.supported-models[0]:gpt-3.5-turbo}")
    private String supportedModel0;
    @Value("${ruoyi.ai.providers.openai.supported-models[1]:gpt-4}")
    private String supportedModel1;

    @Value("${ruoyi.ai.external-ai.openai.timeout:60s}")
    private String timeout;

    @PostConstruct
    public void register() {
        if (apiKey == null || apiKey.isBlank()) {
            log.warn("OpenAI api-key 未配置，Provider 不注册");
            return;
        }
        OpenAiProvider provider = new OpenAiProvider();
        Map<String, Object> cfg = new HashMap<>();
        cfg.put("api-key", apiKey);
        cfg.put("base-url", baseUrl);
        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("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;
        }
    }
}

