package com.backendsys.modules.sdk.bocha.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.backendsys.modules.sdk.bocha.entity.BochaParam;
import com.backendsys.modules.sdk.bocha.entity.BochaResult;
import com.backendsys.modules.sdk.bocha.service.BochaService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class BochaServiceImpl implements BochaService {

    @Value("${bocha.url}")
    private String API_URL;
    @Value("${bocha.api-key}")
    private String API_KEY;

    /**
     * [博查] Web Search API
     * https://bocha-ai.feishu.cn/wiki/RXEOw02rFiwzGSkd9mUcqoeAnNK
     */
    @Override
    public JsonNode WebSearch(BochaParam bochaParam) {

        if (StrUtil.isEmpty(bochaParam.getQuery())) {
            System.out.println("BochaService WebSearch: query 不能为空");
            return null;
        }

        try {

            HttpPost request = new HttpPost(API_URL + "/v1/web-search");
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "Bearer " + API_KEY);

            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(bochaParam);
            request.setEntity(new StringEntity(requestBody, StandardCharsets.UTF_8));

            try (
                CloseableHttpClient client = HttpClients.createDefault();
                CloseableHttpResponse response = client.execute(request)
            ) {

                // 获取响应体
                String responseBody = EntityUtils.toString(response.getEntity());
                // JSONObject jsonResponse = JSONUtil.parseObj(responseBody);

                // 使用 Jackson 解析 JSON (如果出现 null 返回值，则不能使用 JSONObject)
                JsonNode rootNode = objectMapper.readTree(responseBody);
                Integer code = Convert.toInt(rootNode.get("code"));
                JsonNode dataNode = rootNode.path("data");
                if (code == 200) {
                    /*
                    {
                        "webPages": {
                            // 返回值：
                            "value": [
                                { name, url,
                                  snippet,    // 片段
                                  summary,    // 摘要/总结
                                  siteIcon,   // 网站图标
                                  siteName    // 网站名称
                                }
                            ]
                        }
                    }
                     */
                    JsonNode webPagesNode = dataNode.get("webPages");
                    JsonNode valueNode = webPagesNode.get("value");
                    return valueNode;

                } else {
                    return dataNode;
                }

            } catch (Exception e) {
                System.out.println("Exception(1): " + e.getMessage());
                return null;
            }

        } catch (Exception e) {
            System.out.println("Exception(2): " + e.getMessage());
            return null;
        }

    }


    /**
     * [格式化] Web Search API 格式化
     */
    @Override
    public List<BochaResult> WebSearchToList(JsonNode resultList) {
        if (resultList.isArray()) {
            List<BochaResult> bochaResultList = new ArrayList<>();
            for (JsonNode node : resultList) {
                BochaResult bochaResult = new BochaResult();
                bochaResult.setName(node.path("name").asText()); // 根据 JSON 字段名获取值
                bochaResult.setUrl(node.path("url").asText());
                bochaResult.setSummary(node.path("summary").asText());
                bochaResult.setSiteIcon(node.path("siteIcon").asText());
                bochaResult.setSiteName(node.path("siteName").asText());
                bochaResultList.add(bochaResult);
            }
            return bochaResultList;
        } else {
            return null;
        }
    }

    /**
     * [格式化] Web Search API 格式化 (String)
     */
    @Override
    public String WebSearchToString(JsonNode result) {
        List<BochaResult> bochaResultList = WebSearchToList(result);
        if (!bochaResultList.isEmpty()) {
            int index = 1;
            StringBuilder context = new StringBuilder();
            context.append("{");
            for (BochaResult item : bochaResultList) {
                context.append("\"" + index + "\":{"+
                        "\"name\":\"" + item.getName().replace("\"", "\\\"") + "\"," +
                        "\"summary\":\"" + item.getSummary().replace("\"", "\\\"") + "\"," +
                        "\"site_icon\":\"" + item.getSiteIcon().replace("\"", "\\\"") + "\"," +
                        "\"site_name\":\"" + item.getSiteName().replace("\"", "\\\"") + "\"," +
                        "\"url\":\"" + item.getUrl().replace("\"", "\\\"") + "\"" +
                    "}" +
                    ((index == bochaResultList.size()) ? "": ",")
                );

//                context.append("{"+
//                    "\"name\":\"" + item.getName() + "\"," +
//                    "\"summary\":\"" + item.getSummary() + "\"" +
//                    "\"url\":\"" + item.getUrl() + "\"" +
//                "},");

//                context.append("标题: ").append(item.getName()).append("\n");
//                context.append("引用: ").append(item.getSummary()).append("\n");
//                context.append("链接: ").append(item.getUrl()).append("\n\n");

//                context.append("#quote-start# 引用" + index + ": ")
//                        .append(item.getSummary())
//                        .append("#quote-end#；");

                index++;
            }
            context.append("}");
            // 将搜索结果作为上下文添加到消息中
            return context.toString();
        }
        return null;
    }

}
