package com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class HttpClientPoolConfig {
    /**
     * 注册 SSE 专用的 HttpClient 实例
     * （destroyMethod = "close" 确保 Spring 关闭时释放资源）
     */
    @Bean(destroyMethod = "close")
    public CloseableHttpClient sseHttpClient() {
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(1000);                     // 最大连接数
        connManager.setDefaultMaxPerRoute(1000);           // 单路由最大连接数 如果有多个地址，则需要减少
        connManager.setValidateAfterInactivity(30_000);    // 30秒检测空闲连接

        RequestConfig sseConfig = RequestConfig.custom()
                .setConnectTimeout(180000)                  // 连接超时 180s
                .setSocketTimeout(0)                       // 无限等待（SSE 必须）
                .setConnectionRequestTimeout(180000)         // 从池获取连接的超时
                .build();

        return HttpClients.custom()
                .setConnectionManager(connManager)
                .setDefaultRequestConfig(sseConfig)
                .disableAutomaticRetries()                 // 禁用自动重试
                .evictExpiredConnections()                 // 自动清理过期连接
                .evictIdleConnections(60, TimeUnit.SECONDS) // 60秒清理空闲连接
                .build();
    }
}