package com.example.demo.config;

import kong.unirest.Unirest;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.config.RequestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * Unirest HTTP客户端统一配置类
 * 确保Unirest在应用启动时只配置一次，避免重复配置警告
 */
@Configuration
public class UnirestConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(UnirestConfig.class);
    
    // 静态标志，确保只配置一次
    private static volatile boolean configured = false;
    private static final Object lock = new Object();
    
    @PostConstruct
    public void init() {
        configureUnirest();
    }
    
    /**
     * 配置Unirest HTTP客户端
     * 使用双重检查锁定确保线程安全且只配置一次
     */
    public static void configureUnirest() {
        if (!configured) {
            synchronized (lock) {
                if (!configured) {
                    try {
                        logger.info("正在初始化Unirest HTTP客户端配置...");
                        
                        // 先重置，确保干净的状态
                        Unirest.config().reset();
                        
                        // 配置连接池和超时
                        Unirest.config()
                            .connectTimeout(30000)  // 30秒连接超时
                            .socketTimeout(300000)  // 5分钟读取超时（300秒）
                            .retryAfter(false)      // 禁用自动重试，使用自定义重试逻辑
                            .httpClient(HttpClients.custom()
                                .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) // 禁用内部重试
                                .setMaxConnTotal(500)        // 最大连接数
                                .setMaxConnPerRoute(100)     // 每路由最大连接数
                                .setConnectionTimeToLive(30, TimeUnit.SECONDS)
                                .evictExpiredConnections()
                                .evictIdleConnections(30, TimeUnit.SECONDS)
                                .setDefaultRequestConfig(RequestConfig.custom()
                                    .setConnectTimeout(30000)
                                    .setSocketTimeout(300000)
                                    .setConnectionRequestTimeout(30000)
                                    .setContentCompressionEnabled(false) // 禁用压缩，避免额外开销
                                    .build())
                                .build());
                        
                        configured = true;
                        logger.info("Unirest HTTP客户端配置完成: 连接超时30秒, 读取超时300秒");
                        
                    } catch (Exception e) {
                        logger.warn("Unirest配置异常: {}", e.getMessage());
                        // 即使配置失败，也标记为已配置，避免重复尝试
                        configured = true;
                    }
                }
            }
        }
    }
    
    /**
     * 检查是否已配置
     */
    public static boolean isConfigured() {
        return configured;
    }
}
