package com.sino.mci.inbound.mq;

import com.sino.mci.inbound.entity.MessageEvent;
import com.sino.mci.inbound.intent.IntentRecognitionService;
import com.sino.mci.inbound.intent.IntentResult;
import com.sino.mci.inbound.repository.MessageEventMapper;
import com.sino.mci.mq.config.MqConfig;
import com.sino.mci.shared.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 入站消息事件消费者。
 *
 * <p>消费 {@code mci.inbound.queue} 中的事件，进行意图识别，
 * 将识别结果写回业务上下文，并发布到 {@code mci.inbound.flow.exchange}
 * 供流程引擎处理。</p>
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InboundMessageConsumer {

    private final MessageEventMapper messageEventMapper;
    private final IntentRecognitionService intentRecognitionService;
    private final InboundFlowMessageProducer inboundFlowMessageProducer;

    @RabbitListener(queues = MqConfig.INBOUND_QUEUE)
    public void handle(InboundEventMessage message) {
        log.info("收到入站消息事件: eventId={}", message.getEventId());

        MessageEvent event = messageEventMapper.selectById(message.getId());
        if (event == null) {
            log.warn("入站消息事件不存在: eventId={}", message.getEventId());
            return;
        }

        String text = extractText(message.getContent());
        Map<String, Object> businessContext = parseBusinessContext(event.getBusinessContext());

        IntentResult intent = intentRecognitionService.recognize(
                event.getTenantCode(), text, businessContext);

        businessContext.put("intent", intent);
        event.setBusinessContext(JsonUtils.toJson(businessContext));
        event.setIsProcessed(0);
        messageEventMapper.updateById(event);

        inboundFlowMessageProducer.publish(event);
        log.info("入站消息意图识别完成: eventId={}, intent={}, confidence={}",
                event.getEventId(), intent.getIntent(), intent.getConfidence());
    }

    private String extractText(String contentJson) {
        if (contentJson == null || contentJson.isBlank()) {
            return null;
        }
        Map<String, Object> content = JsonUtils.fromJson(contentJson, Map.class);
        if (content == null) {
            return null;
        }
        Object body = content.get("body");
        return body != null ? body.toString() : null;
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> parseBusinessContext(String businessContextJson) {
        if (businessContextJson == null || businessContextJson.isBlank()) {
            return new LinkedHashMap<>();
        }
        Map<String, Object> context = JsonUtils.fromJson(businessContextJson, Map.class);
        return context != null ? context : new LinkedHashMap<>();
    }
}
