package tech.easyflow.ai.documentimport.task;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import tech.easyflow.common.mq.config.MQProperties;
import tech.easyflow.common.mq.core.MQConsumerHandler;
import tech.easyflow.common.mq.core.MQMessage;
import tech.easyflow.common.mq.core.MQSubscription;

import java.util.List;

/**
 * 文档解析任务消费者。
 *
 * @author Codex
 * @since 2026-04-14
 */
@Component
public class DocumentImportParseTaskConsumer implements MQConsumerHandler {

    private static final Logger LOG = LoggerFactory.getLogger(DocumentImportParseTaskConsumer.class);

    private final KnowledgeDocumentImportTaskAppService appService;
    private final MQProperties mqProperties;

    public DocumentImportParseTaskConsumer(KnowledgeDocumentImportTaskAppService appService,
                                          MQProperties mqProperties) {
        this.appService = appService;
        this.mqProperties = mqProperties;
    }

    @Override
    public MQSubscription subscription() {
        MQSubscription subscription = new MQSubscription();
        subscription.setTopic(DocumentImportTaskMqConstants.PARSE_TOPIC);
        subscription.setConsumerGroup(DocumentImportTaskMqConstants.PARSE_GROUP);
        subscription.setShardCount(resolveShardCount());
        return subscription;
    }

    @Override
    public void handle(List<MQMessage> messages) {
        LOG.info("文档解析消费者收到消息批次: count={}", messages == null ? 0 : messages.size());
        for (MQMessage message : messages) {
            DocumentImportTaskMessage event = JSON.parseObject(message.getBody(), DocumentImportTaskMessage.class);
            if (event == null || event.getTaskId() == null) {
                LOG.warn("文档解析消费者跳过非法消息: streamMessageId={}, messageId={}",
                    message == null ? null : message.getStreamMessageId(),
                    message == null ? null : message.getMessageId());
                continue;
            }
            LOG.info("文档解析消费者开始处理消息: taskId={}, messageId={}, streamMessageId={}",
                event.getTaskId(), message.getMessageId(), message.getStreamMessageId());
            try {
                appService.handleParseTask(event.getTaskId());
                LOG.info("文档解析消费者处理完成: taskId={}, messageId={}, streamMessageId={}",
                    event.getTaskId(), message.getMessageId(), message.getStreamMessageId());
            } catch (Exception exception) {
                LOG.error("文档解析消费者处理失败: taskId={}, messageId={}, streamMessageId={}",
                    event.getTaskId(), message.getMessageId(), message.getStreamMessageId(), exception);
                throw exception;
            }
        }
    }

    /**
     * 解析消费者需覆盖生产端的所有分片，避免消息落入未订阅分片。
     *
     * @return 当前 Redis Stream 分片数
     */
    private int resolveShardCount() {
        return Math.max(mqProperties.getRedis().getChatPersistShardCount(), 1);
    }
}
