package com.erp.ai.service.impl;

import com.erp.ai.service.AIChatService;
import com.erp.ai.service.AIModelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * AI模型管理服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AIModelServiceImpl implements AIModelService {

    private final AIChatService aiChatService;

    @Value("${ai.default-service:openai}")
    private String defaultService;

    /**
     * 模型配置
     */
    private static final Map<String, List<Map<String, String>>> MODEL_CONFIGS = new LinkedHashMap<>();

    static {
        MODEL_CONFIGS.put("openai", Arrays.asList(
            Map.of("id", "gpt-4", "name", "GPT-4", "description", "OpenAI最强大的模型"),
            Map.of("id", "gpt-4-turbo", "name", "GPT-4 Turbo", "description", "GPT-4的优化版本"),
            Map.of("id", "gpt-3.5-turbo", "name", "GPT-3.5 Turbo", "description", "性价比高的通用模型"),
            Map.of("id", "gpt-3.5-turbo-instruct", "name", "GPT-3.5 Instruct", "description", "指令优化版本")
        ));

        MODEL_CONFIGS.put("azure_openai", Arrays.asList(
            Map.of("id", "gpt-4", "name", "GPT-4 (Azure)", "description", "Azure托管的GPT-4"),
            Map.of("id", "gpt-35-turbo", "name", "GPT-3.5 Turbo (Azure)", "description", "Azure托管的GPT-3.5")
        ));

        MODEL_CONFIGS.put("anthropic", Arrays.asList(
            Map.of("id", "claude-3-opus-20240229", "name", "Claude 3 Opus", "description", "Anthropic最强大的模型"),
            Map.of("id", "claude-3-sonnet-20240229", "name", "Claude 3 Sonnet", "description", "平衡性能与成本"),
            Map.of("id", "claude-3-haiku-20240307", "name", "Claude 3 Haiku", "description", "快速且经济的模型")
        ));

        MODEL_CONFIGS.put("aliyun_qwen", Arrays.asList(
            Map.of("id", "qwen-max", "name", "通义千问 Max", "description", "阿里云最强大的模型"),
            Map.of("id", "qwen-plus", "name", "通义千问 Plus", "description", "高性能版本"),
            Map.of("id", "qwen-turbo", "name", "通义千问 Turbo", "description", "快速响应版本"),
            Map.of("id", "qwen-7b-chat", "name", "通义千问 7B", "description", "轻量级版本"),
            Map.of("id", "qwen-14b-chat", "name", "通义千问 14B", "description", "中等规模版本")
        ));

        MODEL_CONFIGS.put("local", Collections.singletonList(
            Map.of("id", "local-model", "name", "本地模型", "description", "本地部署的模型")
        ));
    }

    /**
     * 服务显示名称
     */
    private static final Map<String, String> SERVICE_DISPLAY_NAMES = new LinkedHashMap<>();

    static {
        SERVICE_DISPLAY_NAMES.put("openai", "OpenAI");
        SERVICE_DISPLAY_NAMES.put("azure_openai", "Azure OpenAI");
        SERVICE_DISPLAY_NAMES.put("anthropic", "Anthropic Claude");
        SERVICE_DISPLAY_NAMES.put("aliyun_qwen", "阿里云通义千问");
        SERVICE_DISPLAY_NAMES.put("local", "本地模型");
    }

    @Override
    public Map<String, Object> getModels() {
        List<String> availableServices = aiChatService.getAvailableServices();
        String currentService = aiChatService.getCurrentService();
        Map<String, Map<String, Object>> serviceStatus = aiChatService.getServiceStatus();

        Map<String, Map<String, Object>> models = new LinkedHashMap<>();

        for (String service : availableServices) {
            List<Map<String, String>> modelList = MODEL_CONFIGS.getOrDefault(service, Collections.emptyList());
            String displayName = SERVICE_DISPLAY_NAMES.getOrDefault(service, service);
            Map<String, Object> statusInfo = serviceStatus.getOrDefault(service, java.util.Collections.singletonMap("status", (Object) "unknown"));

            Map<String, Object> modelInfo = new LinkedHashMap<>();
            modelInfo.put("service", service);
            modelInfo.put("displayName", displayName);
            modelInfo.put("models", modelList);
            modelInfo.put("currentModel", getCurrentModelForService(service));
            modelInfo.put("status", statusInfo);
            models.put(service, modelInfo);
        }

        return Map.of(
            "models", models,
            "currentService", currentService,
            "serviceStatus", serviceStatus,
            "defaultService", defaultService
        );
    }

    private String getCurrentModelForService(String service) {
        // 从配置或当前状态获取
        return switch (service) {
            case "openai" -> "gpt-3.5-turbo";
            case "aliyun_qwen" -> "qwen-turbo";
            case "anthropic" -> "claude-3-haiku-20240307";
            case "azure_openai" -> "gpt-35-turbo";
            case "local" -> "local-model";
            default -> "";
        };
    }

    @Override
    public Map<String, Object> switchModel(String service, String model, Long userId) {
        // 验证服务
        List<String> availableServices = aiChatService.getAvailableServices();
        if (!availableServices.contains(service)) {
            return Map.of(
                "success", false,
                "error", "不支持的服务: " + service
            );
        }

        // 验证模型
        List<Map<String, String>> serviceModels = MODEL_CONFIGS.getOrDefault(service, Collections.emptyList());
        boolean modelExists = serviceModels.stream()
                .anyMatch(m -> m.get("id").equals(model));

        if (!modelExists) {
            return Map.of(
                "success", false,
                "error", "服务 " + service + " 不支持模型: " + model
            );
        }

        // 切换服务
        aiChatService.setService(service);

        // 测试连接
        Map<String, Object> testResult = aiChatService.testConnection();

        if (!Boolean.TRUE.equals(testResult.get("success"))) {
            return Map.of(
                "success", false,
                "error", "模型切换失败: " + testResult.getOrDefault("message", "连接测试失败"),
                "testResult", testResult
            );
        }

        log.info("用户 {} 切换AI模型到 {}/{}", userId, service, model);

        return Map.of(
            "success", true,
            "service", service,
            "model", model,
            "testResult", testResult,
            "message", "模型切换成功"
        );
    }

    @Override
    public Map<String, Object> getCurrentModel() {
        String currentService = aiChatService.getCurrentService();
        List<Map<String, String>> serviceModels = MODEL_CONFIGS.getOrDefault(currentService, Collections.emptyList());
        String currentModelId = getCurrentModelForService(currentService);

        Map<String, Object> modelInfo = new LinkedHashMap<>();
        modelInfo.put("service", currentService);
        modelInfo.put("serviceDisplayName", SERVICE_DISPLAY_NAMES.getOrDefault(currentService, currentService));
        modelInfo.put("model", currentModelId);

        // 测试连接状态
        Map<String, Object> testResult = aiChatService.testConnection();
        modelInfo.put("status", Boolean.TRUE.equals(testResult.get("success")) ? "online" : "offline");
        modelInfo.put("testMessage", testResult.getOrDefault("message", ""));

        return modelInfo;
    }

    @Override
    public Map<String, Object> testModel(String service, String model) {
        String originalService = aiChatService.getCurrentService();

        try {
            if (service != null && !service.isEmpty() && !service.equals(originalService)) {
                aiChatService.setService(service);
            }

            return aiChatService.testConnection();
        } finally {
            aiChatService.setService(originalService);
        }
    }

    @Override
    public Map<String, Object> getModelStatistics(String period) {
        // 模拟统计数据
        List<Map<String, Object>> popularModels = Arrays.asList(
            Map.of("model", "gpt-3.5-turbo", "count", 800, "percentage", 64),
            Map.of("model", "qwen-max", "count", 300, "percentage", 24),
            Map.of("model", "claude-3-haiku", "count", 150, "percentage", 12)
        );

        List<Map<String, Object>> hourlyUsage = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 24; i++) {
            hourlyUsage.add(Map.of(
                "hour", String.format("%02d:00", i),
                "requests", random.nextInt(91) + 10,
                "tokens", random.nextInt(9001) + 1000
            ));
        }

        return Map.of(
            "period", period,
            "totalRequests", 1250,
            "successfulRequests", 1200,
            "failedRequests", 50,
            "totalTokens", 1250000,
            "avgResponseTime", "1.2秒",
            "popularModels", popularModels,
            "usageByHour", hourlyUsage
        );
    }

    @Override
    public Map<String, Object> getModelRecommendations() {
        String currentService = aiChatService.getCurrentService();
        String currentModel = getCurrentModelForService(currentService);

        List<Map<String, Object>> recommendations = Arrays.asList(
            Map.of(
                "model", "gpt-3.5-turbo",
                "service", "openai",
                "reason", "性价比高，响应速度快，适合日常对话",
                "costPer1kTokens", 0.002,
                "maxTokens", 4096
            ),
            Map.of(
                "model", "qwen-max",
                "service", "aliyun_qwen",
                "reason", "中文理解能力强，适合中文场景",
                "costPer1kTokens", 0.004,
                "maxTokens", 6000
            ),
            Map.of(
                "model", "claude-3-haiku",
                "service", "anthropic",
                "reason", "快速且经济，适合简单任务",
                "costPer1kTokens", 0.00025,
                "maxTokens", 4096
            )
        );

        List<String> selectionCriteria = Arrays.asList(
            "对于简单对话和日常任务，推荐使用 gpt-3.5-turbo",
            "对于中文内容和复杂分析，推荐使用 qwen-max",
            "对于需要快速响应的简单任务，推荐使用 claude-3-haiku",
            "对于需要最高质量的复杂任务，考虑使用 gpt-4 或 claude-3-opus"
        );

        return Map.of(
            "currentModel", currentModel,
            "recommendations", recommendations,
            "selectionCriteria", selectionCriteria
        );
    }
}
