package com.huimv.employment.service.conversation;

import com.huimv.employment.dao.entity.FeConversation;
import com.huimv.employment.dao.mapper.FeConversationMapper;
import com.huimv.employment.integration.kb.KbIntentClassificationClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * 会话意图分类与标题更新（v2 §2.3）。
 * <p>分类能力在智能体侧；本服务仅作为客户端调用智能体 {@code classify-intent}，并落库更新会话标题。</p>
 */
@Service
public class ConversationIntentService {

    private static final Logger log = LoggerFactory.getLogger(ConversationIntentService.class);

    private static final Set<String> STANDARD_INTENTS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
            "employment", "knowledge", "order", "cost", "attendance", "emergency"
    )));

    private final ConversationService conversationService;
    private final FeConversationMapper feConversationMapper;
    private final KbIntentClassificationClient kbIntentClassificationClient;
    private final ConversationIntentClassifier conversationIntentClassifier;

    public ConversationIntentService(ConversationService conversationService,
                                       FeConversationMapper feConversationMapper,
                                       KbIntentClassificationClient kbIntentClassificationClient,
                                       ConversationIntentClassifier conversationIntentClassifier) {
        this.conversationService = conversationService;
        this.feConversationMapper = feConversationMapper;
        this.kbIntentClassificationClient = kbIntentClassificationClient;
        this.conversationIntentClassifier = conversationIntentClassifier;
    }

    /**
     * 首条消息后异步分类并更新标题，不阻塞主对话流。
     */
    @Async
    public void classifyAndUpdateTitleAsync(String sessionId, String userMessage, String agentId) {
        try {
            classifyAndUpdateTitle(sessionId, userMessage, agentId);
        } catch (Exception ex) {
            log.warn("异步意图分类失败 sessionId={}: {}", sessionId, ex.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    void classifyAndUpdateTitle(String sessionId, String userMessage, String agentId) {
        FeConversation conversation = conversationService.requireBySessionId(sessionId);
        String summary = resolveSummary(userMessage, agentId);
        applyClassification(conversation, summary, userMessage);
    }

    private String resolveSummary(String userMessage, String agentId) {
        String upstream = kbIntentClassificationClient.classify(userMessage, agentId);
        if (StringUtils.hasText(upstream)) {
            return upstream.trim();
        }
        return conversationIntentClassifier.classify(userMessage);
    }

    private void applyClassification(FeConversation conversation, String summary, String userMessage) {
        String chatType = resolveChatType(summary);
        String title = resolveTitle(summary, userMessage);

        FeConversation update = new FeConversation();
        update.setId(conversation.getId());
        update.setChatType(chatType);
        update.setTitle(title);
        update.setUpdateTime(LocalDateTime.now());
        feConversationMapper.updateById(update);
        log.debug("会话 {} 意图分类完成 summary={} title={}", conversation.getConversationNo(), summary, title);
    }

    private String resolveChatType(String summary) {
        if (STANDARD_INTENTS.contains(summary)) {
            return summary;
        }
        return "employment";
    }

    private String resolveTitle(String summary, String userMessage) {
        if (!STANDARD_INTENTS.contains(summary)) {
            return truncateTitle(summary);
        }
        switch (summary) {
            case "employment":
                return truncateTitle(StringUtils.hasText(userMessage) ? userMessage : "用工需求咨询");
            case "knowledge":
                return "知识咨询";
            case "order":
                return "订单管理";
            case "cost":
                return truncateTitle(StringUtils.hasText(userMessage) ? userMessage : "成本测算");
            case "attendance":
                return "现场考勤";
            case "emergency":
                return "紧急事件";
            default:
                return truncateTitle(userMessage);
        }
    }

    private static String truncateTitle(String text) {
        if (!StringUtils.hasText(text)) {
            return null;
        }
        String trimmed = text.trim();
        return trimmed.length() <= 200 ? trimmed : trimmed.substring(0, 200);
    }
}
