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.ZhipuAiProvider;
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.zhipu", name = "enabled", havingValue = "true")
public class ZhipuAiProviderConfig {

    private final AiProviderManager providerManager;

    @Value("${ruoyi.ai.external-ai.zhipu.api-key:}")
    private String apiKey;
    @Value("${ruoyi.ai.external-ai.zhipu.base-url:https://open.bigmodel.cn}")
    private String baseUrl;
    @Value("${ruoyi.ai.providers.zhipu.default-model:glm-4}")
    private String defaultModel;
    @Value("${ruoyi.ai.providers.zhipu.supported-models[0]:glm-4}")
    private String supportedModel0;
    @Value("${ruoyi.ai.providers.zhipu.supported-models[1]:glm-3-turbo}")
    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("ZhipuAI api-key 未配置，Provider 不注册");
            return;
        }
        ZhipuAiProvider provider = new ZhipuAiProvider();
        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("ZhipuAI 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;
        }
    }
}
