package tech.easyflow.chatlog.service.impl;

import org.springframework.stereotype.Service;
import tech.easyflow.chatlog.domain.command.ChatRoundSelectCommand;
import tech.easyflow.chatlog.domain.dto.ChatMessageRecord;
import tech.easyflow.chatlog.domain.dto.ChatRoundRecord;
import tech.easyflow.chatlog.service.ChatRoundCommandService;
import tech.easyflow.chatlog.service.ChatRoundOperateService;
import tech.easyflow.chatlog.service.ChatRoundQueryService;
import tech.easyflow.chatlog.support.ChatConstants;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 聊天轮次业务操作服务实现。
 */
@Service
public class ChatRoundOperateServiceImpl implements ChatRoundOperateService {

    private final ChatRoundQueryService chatRoundQueryService;
    private final ChatRoundCommandService chatRoundCommandService;

    public ChatRoundOperateServiceImpl(ChatRoundQueryService chatRoundQueryService,
                                       ChatRoundCommandService chatRoundCommandService) {
        this.chatRoundQueryService = chatRoundQueryService;
        this.chatRoundCommandService = chatRoundCommandService;
    }

    @Override
    public ChatRoundRecord requireRegeneratableRound(BigInteger sessionId, BigInteger roundId) {
        ChatRoundRecord round = requireLatestRound(sessionId, roundId);
        if (round.getSelectedAssistantMessageId() == null || round.getSelectedVariantIndex() == null
                || round.getSelectedVariantIndex() <= 0) {
            throw new BusinessException("当前轮次暂无可重答的回答");
        }
        return round;
    }

    @Override
    public List<ChatMessageRecord> listVariants(BigInteger sessionId, BigInteger roundId) {
        ChatRoundRecord round = chatRoundQueryService.getRound(sessionId, roundId);
        if (round == null) {
            throw new BusinessException("轮次不存在");
        }
        ChatRoundRecord latestRound = chatRoundQueryService.getLatestRound(sessionId);
        boolean switchable = latestRound != null
                && Objects.equals(latestRound.getId(), round.getId())
                && !ChatConstants.ROUND_STATUS_LOCKED.equalsIgnoreCase(round.getStatus());
        List<ChatMessageRecord> variants = new ArrayList<>(chatRoundQueryService.listRoundVariants(sessionId, roundId));
        for (ChatMessageRecord variant : variants) {
            variant.setVariantCount(round.getVariantCount());
            variant.setSelectedVariantIndex(round.getSelectedVariantIndex());
            variant.setSwitchable(switchable);
        }
        return variants;
    }

    @Override
    public ChatMessageRecord selectVariant(BigInteger sessionId, BigInteger roundId, Integer variantIndex, BigInteger operatorId) {
        ChatRoundRecord round = requireLatestRound(sessionId, roundId);
        if (variantIndex == null || variantIndex <= 0) {
            throw new BusinessException("目标答案版本无效");
        }
        ChatMessageRecord selected = chatRoundQueryService.getRoundVariant(sessionId, roundId, variantIndex);
        if (selected == null) {
            throw new BusinessException("目标答案版本不存在");
        }

        ChatRoundSelectCommand command = new ChatRoundSelectCommand();
        command.setSessionId(sessionId);
        command.setRoundId(roundId);
        command.setSelectedVariantIndex(variantIndex);
        command.setSelectedAssistantMessageId(selected.getId());
        command.setSelectedAssistantMessage(selected);
        command.setOperatorId(operatorId);
        chatRoundCommandService.selectVariant(command);
        selected.setSelectedVariantIndex(variantIndex);
        selected.setVariantCount(round.getVariantCount());
        selected.setSwitchable(true);
        return selected;
    }

    private ChatRoundRecord requireLatestRound(BigInteger sessionId, BigInteger roundId) {
        ChatRoundRecord round = chatRoundQueryService.getRound(sessionId, roundId);
        if (round == null) {
            throw new BusinessException("轮次不存在");
        }
        ChatRoundRecord latestRound = chatRoundQueryService.getLatestRound(sessionId);
        if (latestRound == null || !Objects.equals(latestRound.getId(), round.getId())) {
            throw new BusinessException("当前轮次已有后续对话，不支持切换答案版本");
        }
        if (ChatConstants.ROUND_STATUS_LOCKED.equalsIgnoreCase(round.getStatus())) {
            throw new BusinessException("当前轮次已有后续对话，不支持切换答案版本");
        }
        return round;
    }
}
