package com.dora.service;

import com.alibaba.fastjson.JSON;
import com.dora.dto.provider.ProviderTaskRequest;
import com.dora.entity.PointsConfig;
import com.dora.mapper.PointsConfigMapper;
import com.dora.service.provider.AIProvider;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * AI服务提供商路由服务
 * 
 * <p>根据模型配置自动选择合适的服务商Provider
 * 
 * @author 1818AI
 * @since 2025-10-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AIProviderService {

    private final List<AIProvider> providers;
    private final PointsConfigMapper pointsConfigMapper;
    
    private Map<String, AIProvider> providerMap;

    @PostConstruct
    public void init() {
        // 初始化providerMap，key为providerName
        providerMap = new HashMap<>();
        for (AIProvider provider : providers) {
            providerMap.put(provider.getProviderName(), provider);
            log.info("注册AI Provider: {}, 异步: {}", 
                     provider.getProviderName(), provider.isAsyncProvider());
        }
    }

    /**
     * 根据模型名称获取对应的Provider
     * 
     * @param modelName 模型名称
     * @return AI服务提供商
     */
    public AIProvider getProvider(String modelName) {
        // 1. 从points_config表查询模型配置
        PointsConfig config = pointsConfigMapper.findByModelName(modelName);
        if (config == null) {
            throw new IllegalArgumentException("模型不存在: " + modelName);
        }
        
        // 2. 获取providerType
        String providerType = config.getProviderType();
        if (providerType == null || providerType.trim().isEmpty()) {
            providerType = "openai";  // 默认使用openai
        }
        
        // 3. 从providerMap中获取对应的Provider
        AIProvider provider = providerMap.get(providerType);
        if (provider == null) {
            throw new IllegalStateException("不支持的服务商类型: " + providerType);
        }
        
        log.debug("模型 {} 使用服务商: {}", modelName, providerType);
        return provider;
    }

    /**
     * 根据providerType获取Provider
     * 
     * @param providerType 服务商类型
     * @return AI服务提供商
     */
    public AIProvider getProviderByType(String providerType) {
        AIProvider provider = providerMap.get(providerType);
        if (provider == null) {
            throw new IllegalStateException("不支持的服务商类型: " + providerType);
        }
        return provider;
    }

    /**
     * 从PointsConfig中解析providerConfig
     * 
     * @param config 积分配置
     * @return providerConfig的Map格式
     */
    public Map<String, Object> parseProviderConfig(PointsConfig config) {
        String providerConfigJson = config.getProviderConfig();
        if (providerConfigJson == null || providerConfigJson.trim().isEmpty()) {
            return new HashMap<>();
        }
        
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> result = JSON.parseObject(providerConfigJson, Map.class);
            return result;
        } catch (Exception e) {
            log.warn("解析providerConfig失败: {}", providerConfigJson, e);
            return new HashMap<>();
        }
    }

    /**
     * 构建ProviderTaskRequest
     * 
     * @param modelName 模型名称
     * @param prompt 提示词
     * @param imageUrl 图片URL
     * @param imageBase64 图片Base64
     * @param aspectRatio 宽高比
     * @return ProviderTaskRequest对象
     */
    public ProviderTaskRequest buildProviderRequest(
            String modelName, 
            String prompt, 
            String imageUrl, 
            String imageBase64,
            String aspectRatio) {
        
        // 获取模型配置
        PointsConfig config = pointsConfigMapper.findByModelName(modelName);
        Map<String, Object> providerConfig = parseProviderConfig(config);
        
        // 添加taskType到providerConfig中，确保provider能正确识别任务类型
        if (config.getTaskType() != null) {
            providerConfig.put("taskType", config.getTaskType());
        }
        
        return ProviderTaskRequest.builder()
                .modelName(modelName)
                .prompt(prompt)
                .imageUrl(imageUrl)
                .imageBase64(imageBase64)
                .aspectRatio(aspectRatio)
                .providerConfig(providerConfig)
                .build();
    }
}

