package com.seer.teach.common.config.feign;

import feign.Logger;
import feign.Request;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class FeignFullLogger extends Logger {

    @Override
    protected void log(String configKey, String format, Object... args) {
        log.info(String.format(methodTag(configKey) + format, args));
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        Request request = response.request();
        String url = request.url();

        String requestBody = "";
        if (request.body() != null) {
            String bodyStr = new String(request.body());
            requestBody = bodyStr.length() > 200 ? bodyStr.substring(0, 200) + "........." : bodyStr;
        }

        String hostInfo = extractHostFromUrl(url);

        log.info("Feign Request => Method: {}, URL: {}, Host: {}, Headers: {}, Body: {}",
                request.httpMethod().name(),
                url,
                hostInfo,
                request.headers(),
                requestBody);

        String responseBody = "";
        byte[] bodyData = new byte[0];
        try {
            if (response.body() != null) {
                bodyData = Util.toByteArray(response.body().asInputStream());
                String bodyStr = new String(bodyData);
                responseBody = bodyStr.length() > 200 ? bodyStr.substring(0, 200) + "........." : bodyStr;
            }
        } catch (IOException e) {
            log.warn("Failed to read response body", e);
            responseBody = "[Failed to read response body]";
        }

        log.info("Feign Response <= Status: {}, Headers: {}, Body: {}, Time: {}ms",
                response.status(),
                response.headers(),
                responseBody,
                elapsedTime);

        return response.toBuilder().body(bodyData).build();
    }

    /**
     * 从URL中提取主机信息
     * @param url 完整URL
     * @return 主机信息（IP:Port）
     */
    private String extractHostFromUrl(String url) {
        try {
            int protocolEnd = url.indexOf("://");
            if (protocolEnd != -1) {
                int pathStart = url.indexOf("/", protocolEnd + 3);
                if (pathStart != -1) {
                    return url.substring(protocolEnd + 3, pathStart);
                } else {
                    return url.substring(protocolEnd + 3);
                }
            }
        } catch (Exception e) {
            log.debug("Failed to extract host from URL: {}", url, e);
        }
        return "unknown";
    }

}
