package com.ruoyi.jarvis.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 调用金山文档开放平台 HTTP 接口（含 OAuth 换票与 Open API）
 */
public final class KdocsOpenApiClient {

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

    static {
        System.setProperty("java.net.useSystemProxies", "false");
    }

    private KdocsOpenApiClient() {
    }

    /**
     * 请求 JSON 接口，返回根对象（含 code、data）
     *
     * @param jsonContentTypeForGet 部分 GET（如 oauth2/access_token）要求 Content-Type: application/json
     */
    public static JSONObject exchange(String method, String fullUrl, String jsonBody, boolean jsonContentTypeForGet) {
        try {
            URL u = new URL(fullUrl);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection(java.net.Proxy.NO_PROXY);
            conn.setRequestMethod(method);
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "application/json");
            if ("GET".equals(method) && jsonContentTypeForGet) {
                conn.setRequestProperty("Content-Type", "application/json");
            }
            if ("POST".equals(method) || "PUT".equals(method)) {
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                if (jsonBody != null && !jsonBody.isEmpty()) {
                    try (OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8)) {
                        w.write(jsonBody);
                        w.flush();
                    }
                }
            }

            int status = conn.getResponseCode();
            StringBuilder sb = new StringBuilder();
            InputStream stream = status >= 200 && status < 300 ? conn.getInputStream() : conn.getErrorStream();
            if (stream != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                }
            }
            String text = sb.toString();
            log.debug("Kdocs HTTP {} {} -> {} body: {}", method, fullUrl, status, text.length() > 500 ? text.substring(0, 500) + "..." : text);
            if (status < 200 || status >= 300) {
                throw new RuntimeException("HTTP " + status + ": " + text);
            }
            if (StringUtils.isBlank(text)) {
                return new JSONObject();
            }
            return JSON.parseObject(text);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Kdocs 请求失败: " + e.getMessage(), e);
        }
    }

    /**
     * 业务 Open API：code 必须为 0，返回 data
     */
    public static JSONObject requireBusinessData(JSONObject root) {
        if (root == null) {
            throw new RuntimeException("Kdocs 响应为空");
        }
        Integer c = root.getInteger("code");
        if (c == null || c != 0) {
            throw new RuntimeException("Kdocs 业务错误: " + root.toJSONString());
        }
        JSONObject data = root.getJSONObject("data");
        return data != null ? data : new JSONObject();
    }
}
