package com.agent.management.repository;

import com.agent.management.model.entity.AiModel;
import com.agent.management.repository.json.AbstractJsonRepository;
import com.agent.management.repository.json.JsonStore;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * AI 模型配置仓库（JSON 文件实现）
 *
 * 数据文件：data/json/ai-models.json
 */
@Component
public class AiModelRepository extends AbstractJsonRepository<AiModel> {

    public AiModelRepository(JsonStore store) {
        super(store, new TypeReference<>() {});
    }

    @Override
    protected String getFileName() {
        return "ai-models.json";
    }

    @Override
    protected Long getId(AiModel entity) {
        return entity.getId();
    }

    @Override
    protected void setId(AiModel entity, Long id) {
        entity.setId(id);
    }

    public Optional<AiModel> findByIsDefaultTrue() {
        return findAll().stream()
                .filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
                .findFirst();
    }

    /** 按调用优先级排序：默认模型优先，然后按 priority 升序 */
    public List<AiModel> findAllByOrderByIsDefaultDescPriorityAscCreatedAtAsc() {
        List<AiModel> list = new java.util.ArrayList<>(findAll());
        list.sort(Comparator
                .comparing((AiModel m) -> Boolean.TRUE.equals(m.getIsDefault()) ? 0 : 1)
                .thenComparingInt(m -> m.getPriority() == null ? Integer.MAX_VALUE : m.getPriority())
                .thenComparing(m -> m.getCreatedAt() == null ? java.time.LocalDateTime.MAX : m.getCreatedAt()));
        return list;
    }
}
