package cn.reghao.tnb.gateway.limiter;

import lombok.extern.slf4j.Slf4j;
//import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 根据 CPU 使用率限流(需要 spring-boot-starter-actuator 依赖)
 *
 * @author reghao
 * @date 2025-07-16 10:02:14
 */
@Slf4j
@Component
public class MetricsRateLimiterFilter implements GatewayFilter, Ordered {
    private static final String METRIC_NAME = "system.cpu.usage";
    private static final double MAX_USAGE = 0.50D;
    /*private final MetricsEndpoint metricsEndpoint;

    public MetricsRateLimiterFilter(MetricsEndpoint metricsEndpoint) {
        this.metricsEndpoint = metricsEndpoint;
    }*/

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        double systemCpuUsage = getCpuUsage();
        boolean ok = systemCpuUsage < MAX_USAGE;
        log.debug("system.cpu.usage: " + systemCpuUsage + " ok: " + ok);
        if (!ok) {
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        } else {
            return chain.filter(exchange);
        }
    }

    private double getCpuUsage() {
        /*double usage = metricsEndpoint.metric(METRIC_NAME, null)
                .getMeasurements()
                .stream()
                .filter(Objects::nonNull)
                .findFirst()
                .map(MetricsEndpoint.Sample::getValue)
                .filter(Double::isFinite)
                .orElse(0.0D);*/
        return 0.0D;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
