package com.inspect.analysis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class SimpleHttpClient {
    private static final Logger log = LoggerFactory.getLogger(SimpleHttpClient.class);

    private static final int DEFAULT_TIMEOUT_MS = 30000;

    public static String doPostJson(String url, String jsonBody) throws IOException {
        return doPostJson(url, jsonBody, null, DEFAULT_TIMEOUT_MS);
    }

    public static String doPostJson(String url, String jsonBody, Map<String, String> headers, int timeoutMs) throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(timeoutMs);
            conn.setReadTimeout(timeoutMs);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonBody.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

            int responseCode = conn.getResponseCode();
            InputStream is = (responseCode >= 400) ? conn.getErrorStream() : conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            if (responseCode >= 400) {
                throw new IOException("HTTP POST failed with status " + responseCode + ": " + result);
            }

            return result.toString();

        } finally {
            if (reader != null) try { reader.close(); } catch (IOException ignore) {}
            if (conn != null) conn.disconnect();
        }
    }

    public static String doGet(String url) throws IOException {
        return doGet(url, null, DEFAULT_TIMEOUT_MS);
    }

    public static String doGet(String url, Map<String, String> headers, int timeoutMs) throws IOException {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        try {
            URL realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(timeoutMs);
            conn.setReadTimeout(timeoutMs);
            conn.setRequestProperty("Accept", "application/json");

            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            int responseCode = conn.getResponseCode();
            InputStream is = (responseCode >= 400) ? conn.getErrorStream() : conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            if (responseCode >= 400) {
                log.error("HTTP GET Failed: {}", responseCode + " - " + result);
            }

            return result.toString();

        } catch (IOException ex) {
            log.error("HTTP GET 请求异常: {}", ex.getClass().getSimpleName() + " - " + ex.getMessage());
            throw ex;
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException ignore) {}
            if (conn != null) conn.disconnect();
        }
    }
}

