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.FastGptProvider;
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.ai-platform.fastgpt", name = "enabled", havingValue = "true")
public class FastGptPlatformConfig {

    private final AiProviderManager providerManager;

    @Value("${ruoyi.ai.ai-platform.fastgpt.api-key:}")
    private String apiKey;
    @Value("${ruoyi.ai.ai-platform.fastgpt.base-url:}")
    private String baseUrl;
    @Value("${ruoyi.ai.ai-platform.fastgpt.default-app-id:}")
    private String defaultAppId;
    @Value("${ruoyi.ai.providers.fastgpt.supported-models[0]:fastgpt}")
    private String supportedModel0;
    @Value("${ruoyi.ai.external-ai.openai.timeout:60s}")
    private String timeout;

    @PostConstruct
    public void register() {
        if (apiKey == null || apiKey.isBlank() || baseUrl == null || baseUrl.isBlank() || defaultAppId == null || defaultAppId.isBlank()) {
            log.warn("FastGPT 配置不完整，Provider 不注册");
            return;
        }
        FastGptProvider provider = new FastGptProvider();
        Map<String, Object> cfg = new HashMap<>();
        cfg.put("api-key", apiKey);
        cfg.put("base-url", baseUrl);
        cfg.put("default-app-id", defaultAppId);
        cfg.put("timeout-ms", parseTimeoutMs(timeout));
        cfg.put("supported-models", List.of(supportedModel0));
        provider.initialize(cfg);
        providerManager.registerProvider(provider);
        log.info("FastGPT 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;
        }
    }
}
