package tech.easyflow.ai.service.discovery;

import org.springframework.stereotype.Component;
import tech.easyflow.ai.entity.Model;
import tech.easyflow.ai.service.capability.ModelCapabilityCatalog;
import tech.easyflow.ai.service.capability.ModelCapabilityResolution;
import tech.easyflow.ai.service.capability.ModelCapabilityResolver;
import tech.easyflow.ai.service.capability.ModelCatalogMetadata;

import java.util.Optional;

/**
 * 使用静态模型目录和统一能力规则补全远端模型信息。
 */
@Component
public class RemoteModelMetadataResolver {

    /** 数据库允许的最大模型 ID 长度。 */
    private static final int MAX_MODEL_ID_LENGTH = 255;
    /** 数据库允许的最大模型标题长度。 */
    private static final int MAX_TITLE_LENGTH = 128;
    /** 未命中目录时使用的默认家族。 */
    private static final String DEFAULT_FAMILY = "其他模型";

    /** 静态模型目录。 */
    private final ModelCapabilityCatalog catalog;
    /** 统一模型能力解析器。 */
    private final ModelCapabilityResolver capabilityResolver;

    /**
     * 创建远端模型元数据解析器。
     *
     * @param catalog 静态模型目录
     * @param capabilityResolver 统一模型能力解析器
     */
    public RemoteModelMetadataResolver(ModelCapabilityCatalog catalog,
                                       ModelCapabilityResolver capabilityResolver) {
        this.catalog = catalog;
        this.capabilityResolver = capabilityResolver;
    }

    /**
     * 构建管理端使用的远端模型描述。
     *
     * @param providerType 供应商类型
     * @param modelId 远端原始模型 ID
     * @param added 是否已经添加
     * @return 统一模型描述
     */
    public RemoteModelDescriptor describe(String providerType, String modelId, boolean added) {
        Optional<ModelCatalogMetadata> metadata = catalog.findMetadata(providerType, modelId);
        ModelCapabilityResolution capability = capabilityResolver.resolve(providerType, modelId);
        boolean addable = modelId.codePointCount(0, modelId.length()) <= MAX_MODEL_ID_LENGTH;
        return new RemoteModelDescriptor(
                modelId,
                metadata.map(ModelCatalogMetadata::getDisplayName)
                        .filter(value -> !value.isBlank()).orElse(modelId),
                metadata.map(ModelCatalogMetadata::getFamily)
                        .filter(value -> !value.isBlank()).orElse(DEFAULT_FAMILY),
                capability.getModelType(),
                capability.getSupportImage(),
                capability.getSupportThinking(),
                capability.getSupportTool(),
                capability.getSource(),
                added,
                addable,
                addable ? null : "模型 ID 超过 255 个字符");
    }

    /**
     * 使用目录元数据和能力识别结果配置待新增模型。
     *
     * @param target 待新增模型
     * @param providerType 供应商类型
     * @param modelId 远端原始模型 ID
     */
    public void configureNewModel(Model target, String providerType, String modelId) {
        Optional<ModelCatalogMetadata> metadata = catalog.findMetadata(providerType, modelId);
        ModelCapabilityResolution capability = capabilityResolver.resolve(providerType, modelId);
        String displayName = metadata.map(ModelCatalogMetadata::getDisplayName)
                .filter(value -> !value.isBlank()).orElse(modelId);
        String family = metadata.map(ModelCatalogMetadata::getFamily)
                .filter(value -> !value.isBlank()).orElse(DEFAULT_FAMILY);

        target.setModelName(modelId);
        target.setTitle(limitCodePoints(displayName, MAX_TITLE_LENGTH));
        target.setGroupName(family);
        target.setModelType(capability.getModelType());
        target.setSupportImage(capability.getSupportImage());
        target.setSupportThinking(capability.getSupportThinking());
        target.setSupportTool(capability.getSupportTool());
        target.setSupportToolMessage(capability.getSupportTool());
        target.setSupportImageB64Only(Boolean.FALSE);
        target.setSupportVideo(Boolean.FALSE);
        target.setSupportAudio(Boolean.FALSE);
        target.setSupportFree(Boolean.FALSE);
        target.setPublishEnabled(Boolean.FALSE);
    }

    /**
     * 判断目录中的模型是否为尚未接入的生成模型。
     *
     * @param providerType 供应商类型
     * @param modelId 远端原始模型 ID
     * @return 已知仅生成图片、视频或音频时返回 true
     */
    public boolean isUnsupportedGenerationModel(String providerType, String modelId) {
        return catalog.findMetadata(providerType, modelId)
                .map(ModelCatalogMetadata::isUnsupportedGenerationModel)
                .orElse(false);
    }

    /**
     * 按 Unicode 码点安全截断文本。
     *
     * @param value 原始文本
     * @param maxCodePoints 最大码点数
     * @return 截断后的文本
     */
    private String limitCodePoints(String value, int maxCodePoints) {
        if (value.codePointCount(0, value.length()) <= maxCodePoints) {
            return value;
        }
        int endIndex = value.offsetByCodePoints(0, maxCodePoints);
        return value.substring(0, endIndex);
    }
}
