package com.ruoyi.aicall.utils;

import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class ClientIpCheck {

    public static Boolean checkIp(HttpServletRequest request){
        String clientIp = getClientIp(request);
        ICcParamsService ccParamsService = SpringUtils.getBean(ICcParamsService.class);
        String whiteIpList = ccParamsService.getParamValueByCode("api-client-white-ips", "");
        if (StringUtils.isNotEmpty(whiteIpList)) {
            if (whiteIpList.contains("0.0.0.0")) {
                return true;
            }
            for (String ip: whiteIpList.split(",")) {
                if (ip.equals(clientIp)) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 解析客户端 IP，并打印诊断日志（XFF / X-Real-IP / remoteAddr / 选用源 / URI）。
     * 用于排查偶发 172.17.0.1（docker0）与公网 IP 并存的问题。
     */
    public static String getClientIp(HttpServletRequest request) {
        String xff = request.getHeader("X-Forwarded-For");
        String xRealIp = request.getHeader("X-Real-IP");
        String proxyClientIp = request.getHeader("Proxy-Client-IP");
        String wlProxyClientIp = request.getHeader("WL-Proxy-Client-IP");
        String httpClientIp = request.getHeader("HTTP_CLIENT_IP");
        String httpXff = request.getHeader("HTTP_X_FORWARDED_FOR");
        String remoteAddr = request.getRemoteAddr();
        String uri = request.getRequestURI();
        String query = request.getQueryString();

        String[][] headerCandidates = {
                {"X-Forwarded-For", xff},
                {"X-Real-IP", xRealIp},
                {"Proxy-Client-IP", proxyClientIp},
                {"WL-Proxy-Client-IP", wlProxyClientIp},
                {"HTTP_CLIENT_IP", httpClientIp},
                {"HTTP_X_FORWARDED_FOR", httpXff}
        };

        String chosenSource = "remoteAddr";
        String clientIp = remoteAddr;
        for (String[] item : headerCandidates) {
            String name = item[0];
            String value = item[1];
            if (value != null && !value.isEmpty() && !"unknown".equalsIgnoreCase(value)) {
                clientIp = value.split(",")[0].trim();
                chosenSource = name;
                break;
            }
        }

        log.info("get client ip:{}, source={}, X-Forwarded-For={}, X-Real-IP={}, remoteAddr={}, uri={}{}",
                clientIp,
                chosenSource,
                emptyToDash(xff),
                emptyToDash(xRealIp),
                emptyToDash(remoteAddr),
                uri,
                query == null ? "" : ("?" + query));

        return clientIp;
    }

    private static String emptyToDash(String value) {
        if (value == null || value.isEmpty()) {
            return "-";
        }
        return value;
    }
}
