package top.tqx.demo_1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.tqx.demo_1.config.AiApiConfig;
import top.tqx.demo_1.dto.KBRouteRequest;
import top.tqx.demo_1.dto.KBRouteResponse;
import top.tqx.demo_1.service.KBRouteService;
import top.tqx.demo_1.service.RagService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class KBRouteServiceImpl implements KBRouteService {

    @Autowired
    private AiApiConfig aiApiConfig;

    @Autowired
    private RagService ragService;

    @Override
    public KBRouteResponse route(KBRouteRequest request) throws IOException {
        String url = aiApiConfig.getFullUrl(aiApiConfig.getKbRoute().getRoute());
        log.info("调用RAG服务知识库路由: url={}", url);

        try {
            ObjectNode requestBody = ragService.createObjectNode();
            if (request.getQuery() != null) {
                requestBody.put("query", request.getQuery());
            }

            String jsonResponse = ragService.postJsonRequest(url, requestBody.toString(), 30000);
            JsonNode rootNode = ragService.parseJson(jsonResponse);
            log.info("RAG服务知识库路由成功");

            KBRouteResponse response = new KBRouteResponse();

            if (rootNode.has("query")) {
                response.setQuery(rootNode.get("query").asText());
            }
            if (rootNode.has("user_role")) {
                response.setUserRole(rootNode.get("user_role").asText());
            }
            if (rootNode.has("user_department")) {
                response.setUserDepartment(rootNode.get("user_department").asText());
            }

            if (rootNode.has("target_collections") && rootNode.get("target_collections").isArray()) {
                List<String> targetCollections = new ArrayList<>();
                for (JsonNode collectionNode : rootNode.get("target_collections")) {
                    targetCollections.add(collectionNode.asText());
                }
                response.setTargetCollections(targetCollections);
            }

            if (rootNode.has("intent") && rootNode.get("intent").isObject()) {
                JsonNode intentNode = rootNode.get("intent");
                KBRouteResponse.IntentData intent = new KBRouteResponse.IntentData();

                if (intentNode.has("is_general")) {
                    intent.setIsGeneral(intentNode.get("is_general").asBoolean());
                }
                if (intentNode.has("department")) {
                    intent.setDepartment(intentNode.get("department").asText());
                }
                if (intentNode.has("confidence")) {
                    intent.setConfidence(intentNode.get("confidence").asDouble());
                }
                if (intentNode.has("reason")) {
                    intent.setReason(intentNode.get("reason").asText());
                }

                if (intentNode.has("keywords") && intentNode.get("keywords").isArray()) {
                    List<String> keywords = new ArrayList<>();
                    for (JsonNode keywordNode : intentNode.get("keywords")) {
                        keywords.add(keywordNode.asText());
                    }
                    intent.setKeywords(keywords);
                }

                response.setIntent(intent);
            }

            return response;

        } catch (Exception e) {
            log.error("调用RAG服务知识库路由失败: {}", e.getMessage(), e);
            return new KBRouteResponse();
        }
    }
}
