package com.huimv.employment.integration.kb;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

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

/**
 * 转发至智能体 {@code POST /api/mcp/conversation/classify-intent}。
 */
@Service
public class KbIntentClassificationClientImpl implements KbIntentClassificationClient {

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

    private static final String HEADER_AGENT_ID = "X-Agent-Id";
    private static final String PATH_CLASSIFY = "/api/mcp/conversation/classify-intent";

    private final KbApiProperties properties;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public KbIntentClassificationClientImpl(KbApiProperties properties,
                                              @Qualifier("kbRestTemplate") RestTemplate restTemplate,
                                              ObjectMapper objectMapper) {
        this.properties = properties;
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @Override
    public String classify(String userMessage, String agentId) {
        if (!properties.isEnabled() || !StringUtils.hasText(userMessage)) {
            return null;
        }
        try {
            Map<String, Object> body = new LinkedHashMap<>();
            body.put("user_message", userMessage.trim());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            properties.applyAuthHeader(headers);
            headers.add(HEADER_AGENT_ID, resolveAgentId(agentId));
            ResponseEntity<String> response = restTemplate.exchange(
                    properties.baseUrl() + PATH_CLASSIFY,
                    HttpMethod.POST,
                    new HttpEntity<>(body, headers),
                    String.class);
            return parseSummary(response.getBody());
        } catch (RestClientException ex) {
            log.debug("上游意图分类不可用，将使用本地兜底：{}", ex.getMessage());
            return null;
        } catch (Exception ex) {
            log.warn("解析上游意图分类响应失败：{}", ex.getMessage());
            return null;
        }
    }

    private String parseSummary(String raw) throws Exception {
        if (!StringUtils.hasText(raw)) {
            return null;
        }
        JsonNode root = objectMapper.readTree(raw.trim());
        JsonNode data = root.path("data");
        if (!data.isMissingNode() && data.has("summary")) {
            return textValue(data.get("summary"));
        }
        if (root.has("summary")) {
            return textValue(root.get("summary"));
        }
        return null;
    }

    private static String textValue(JsonNode node) {
        if (node == null || node.isNull()) {
            return null;
        }
        String text = node.asText(null);
        return StringUtils.hasText(text) ? text.trim() : null;
    }

    private String resolveAgentId(String agentId) {
        if (StringUtils.hasText(agentId)) {
            return agentId.trim();
        }
        return properties.getDefaultAgentId();
    }
}
