package org.dromara.ai.controller.admin;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.dromara.ai.domain.dto.AiModelInfo;
import org.dromara.ai.service.AiModelService;
import org.dromara.common.core.domain.R;
import org.dromara.common.web.core.BaseController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统模型管理
 *
 * @author pengles
 */
@Tag(name = "管理端-系统模型管理", description = "系统模型管理接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/model")
public class AdminSysModelController extends BaseController {

    private final AiModelService aiModelService;

    /**
     * 获取模型列表（用于前端下拉选择）
     */
    @Operation(summary = "获取模型列表", description = "获取所有可用模型列表，用于前端下拉选择")
    @GetMapping("/modelList")
    public R<List<Map<String, Object>>> modelList() {
        List<AiModelInfo> models = aiModelService.getAllModels();
        List<Map<String, Object>> data = models.stream()
            .filter(m -> Boolean.TRUE.equals(m.getAvailable()))
            .filter(m -> m.getStatus() == null || m.getStatus() == AiModelInfo.ModelStatus.AVAILABLE)
            .map(this::toFrontendModel)
            .collect(Collectors.toList());
        return R.ok(data);
    }

    /**
     * 根据分类获取模型列表
     */
    @Operation(summary = "根据分类获取模型列表", description = "根据类型或Provider分类获取模型列表")
    @GetMapping("/list")
    public R<List<Map<String, Object>>> listByCategory(
            @Parameter(description = "分类（类型或Provider）") @RequestParam(required = false) String category) {
        List<AiModelInfo> models = aiModelService.getAllModels();
        List<Map<String, Object>> data = models.stream()
            .filter(m -> {
                if (category == null || category.isBlank()) return true;
                boolean byType = m.getType() != null && category.equalsIgnoreCase(m.getType().getCode());
                boolean byProvider = m.getProvider() != null && category.equalsIgnoreCase(m.getProvider());
                return byType || byProvider;
            })
            .map(this::toFrontendModel)
            .collect(Collectors.toList());
        return R.ok(data);
    }

    /**
     * 转换为前端模型格式
     */
    private Map<String, Object> toFrontendModel(AiModelInfo m) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("modelName", m.getId());
        map.put("modelDescribe", Optional.ofNullable(m.getDisplayName()).orElse(Optional.ofNullable(m.getName()).orElse(m.getId())));
        List<String> caps = Optional.ofNullable(m.getCapabilities()).orElse(List.of())
            .stream().map(AiModelInfo.ModelCapability::getCode).collect(Collectors.toList());
        map.put("modelCapability", caps);
        List<Map<String, String>> abilities = Optional.ofNullable(m.getCapabilities()).orElse(List.of())
            .stream().map(c -> {
                Map<String, String> a = new HashMap<>();
                a.put("name", c.getCode());
                a.put("description", c.getName());
                return a;
            }).collect(Collectors.toList());
        map.put("modelAbilities", abilities);
        return map;
    }
}
