package com.infoepoch.pms.agent.platform.chatbot.application;

import com.infoepoch.pms.agent.platform.agent.domain.Agent;
import com.infoepoch.pms.agent.platform.agent.domain.irepository.IAgentRepository;
import com.infoepoch.pms.agent.platform.chatbot.domain.irepository.IChatbotAgentsRepository;
import com.infoepoch.pms.agent.platform.chatbot.domain.irepository.IChatbotRepository;
import com.infoepoch.pms.agent.platform.chatbot.domain.Chatbot;
import com.infoepoch.pms.agent.platform.chatbot.domain.ChatbotAgents;
import com.infoepoch.pms.agent.platform.model.application.ModelQueryService;
import com.infoepoch.pms.agent.platform.model.domain.AiModelConfig;
import com.infoepoch.pms.agent.platform.shared.exception.BusinessException;
import com.infoepoch.pms.agent.platform.shared.response.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 聊天机器人查询服务。
 */
@Service
@RequiredArgsConstructor
public class ChatbotQueryService {

    private final IChatbotRepository chatbotRepository;
    private final IChatbotAgentsRepository chatbotAgentsRepository;
    private final IAgentRepository agentRepository;
    private final ModelQueryService modelQueryService;

    /**
     * 按 ID 查询启用中的聊天机器人。
     *
     * @param id 聊天机器人主键
     * @return 启用中的聊天机器人；不存在或已禁用时返回空
     */
    @Transactional(readOnly = true)
    public Optional<Chatbot> findEnabledById(String id) {
        return chatbotRepository.findById(id)
                .map(this::attachRelations)
                .filter(Chatbot::isEnabled);
    }

    /**
     * 按 ID 查询聊天机器人详情，并预加载模型配置与子智能体。
     *
     * @param id 聊天机器人主键
     * @return 聊天机器人详情
     */
    @Transactional(readOnly = true)
    public Optional<Chatbot> findDetailById(String id) {
        return chatbotRepository.findById(id).map(this::attachRelations);
    }

    /**
     * 查询全部聊天机器人详情并按创建时间倒序返回。
     *
     * @return 聊天机器人详情列表
     */
    @Transactional(readOnly = true)
    public List<Chatbot> listDetails() {
        return chatbotRepository.findAllByOrderByCreatedAtDesc().stream()
                .map(this::attachRelations)
                .toList();
    }

    private Chatbot attachRelations(Chatbot chatbot) {
        if (chatbot == null) {
            return null;
        }
        AiModelConfig modelConfig = modelQueryService.getModelConfigOrNull(chatbot.getModelConfigId());
        chatbot.setModelConfig(modelConfig);
        Set<Agent> subAgents = new LinkedHashSet<>();
        for (ChatbotAgents relation : chatbotAgentsRepository.findByChatBotId(chatbot.getId())) {
            Agent agent = agentRepository.findById(relation.getAgentId())
                    .orElseThrow(() -> new BusinessException(ResultCode.AGENT_NOT_FOUND,
                            "子智能体 ID=" + relation.getAgentId() + " 不存在"));
            subAgents.add(agent);
        }
        chatbot.setSubAgents(subAgents);
        return chatbot;
    }
}
