package top.tqx.demo_1.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Service
public class RagService {

    @Autowired
    private AiApiConfig aiApiConfig;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public String postJsonRequest(String url, Map<String, Object> requestBody, int timeoutMs) throws IOException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonBody = mapper.writeValueAsString(requestBody);
            return doPostJsonRequest(url, jsonBody, timeoutMs);
        } catch (Exception e) {
            throw new IOException("序列化请求体失败: " + e.getMessage(), e);
        }
    }

    public String postJsonRequest(String url, String jsonBody, int timeoutMs) throws IOException {
        return doPostJsonRequest(url, jsonBody, timeoutMs);
    }

    private String doPostJsonRequest(String url, String jsonBody, int timeoutMs) throws IOException {
        try {
            java.net.URL requestUrl = new java.net.URL(url);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(timeoutMs);

            connection.connect();

            try (java.io.OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            log.info("RAG服务响应状态码: {}", responseCode);

            if (responseCode != 200) {
                StringBuilder errorResponse = new StringBuilder();
                try (java.io.BufferedReader reader = new java.io.BufferedReader(
                        new java.io.InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                } catch (Exception e) {
                    log.warn("读取RAG服务错误响应失败: {}", e.getMessage());
                }
                String errorMsg = "RAG服务返回错误状态码: " + responseCode;
                if (errorResponse.length() > 0) {
                    errorMsg += ", 错误信息: " + errorResponse.toString();
                    log.error("RAG服务错误响应内容: {}", errorResponse.toString());
                }
                throw new IOException(errorMsg);
            }

            StringBuilder response = new StringBuilder();
            try (java.io.BufferedReader reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }

            connection.disconnect();
            return response.toString();

        } catch (java.net.SocketTimeoutException e) {
            throw new IOException("请求超时: " + e.getMessage(), e);
        } catch (java.net.UnknownHostException e) {
            throw new IOException("无法连接RAG服务，请检查服务地址: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new IOException("调用RAG服务失败: " + e.getMessage(), e);
        }
    }

    public String getRequest(String url, int timeoutMs) throws IOException {
        try {
            java.net.URL requestUrl = new java.net.URL(url);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(timeoutMs);

            connection.connect();

            int responseCode = connection.getResponseCode();
            log.info("RAG服务响应状态码: {}", responseCode);

            if (responseCode != 200) {
                StringBuilder errorResponse = new StringBuilder();
                try (java.io.BufferedReader reader = new java.io.BufferedReader(
                        new java.io.InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                } catch (Exception e) {
                    log.warn("读取RAG服务错误响应失败: {}", e.getMessage());
                }
                String errorMsg = "RAG服务返回错误状态码: " + responseCode;
                if (errorResponse.length() > 0) {
                    errorMsg += ", 错误信息: " + errorResponse.toString();
                    log.error("RAG服务错误响应内容: {}", errorResponse.toString());
                }
                throw new IOException(errorMsg);
            }

            StringBuilder response = new StringBuilder();
            try (java.io.BufferedReader reader = new java.io.BufferedReader(
                    new java.io.InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }

            connection.disconnect();
            return response.toString();

        } catch (java.net.SocketTimeoutException e) {
            throw new IOException("请求超时: " + e.getMessage(), e);
        } catch (java.net.UnknownHostException e) {
            throw new IOException("无法连接RAG服务，请检查服务地址: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new IOException("调用RAG服务失败: " + e.getMessage(), e);
        }
    }

    public String getJsonRequest(String url, int timeoutMs) throws IOException {
        return getRequest(url, timeoutMs);
    }

    public byte[] getBinaryRequest(String url, int timeoutMs) throws IOException {
        try {
            java.net.URL requestUrl = new java.net.URL(url);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) requestUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(timeoutMs);

            connection.connect();

            int responseCode = connection.getResponseCode();
            log.info("RAG服务响应状态码: {}", responseCode);

            if (responseCode != 200) {
                StringBuilder errorResponse = new StringBuilder();
                try (java.io.BufferedReader reader = new java.io.BufferedReader(
                        new java.io.InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        errorResponse.append(line);
                    }
                } catch (Exception e) {
                    log.warn("读取RAG服务错误响应失败: {}", e.getMessage());
                }
                String errorMsg = "RAG服务返回错误状态码: " + responseCode;
                if (errorResponse.length() > 0) {
                    errorMsg += ", 错误信息: " + errorResponse.toString();
                    log.error("RAG服务错误响应内容: {}", errorResponse.toString());
                }
                throw new IOException(errorMsg);
            }

            try (java.io.InputStream is = connection.getInputStream()) {
                return is.readAllBytes();
            }

        } catch (java.net.SocketTimeoutException e) {
            throw new IOException("请求超时: " + e.getMessage(), e);
        } catch (java.net.UnknownHostException e) {
            throw new IOException("无法连接RAG服务，请检查服务地址: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new IOException("调用RAG服务失败: " + e.getMessage(), e);
        }
    }

    public JsonNode parseJson(String json) throws IOException {
        return objectMapper.readTree(json);
    }

    public ObjectNode createObjectNode() {
        return objectMapper.createObjectNode();
    }

    public ObjectMapper getObjectMapper() {
        return objectMapper;
    }
}