using System.Collections.Concurrent;

namespace Yi.Framework.AiHub.Domain.AiGateWay;

public static class HttpClientFactory
{
    /// <summary>
    /// HttpClient池总数
    /// </summary>
    /// <returns></returns>
    private static int _poolSize;

    private static int PoolSize
    {
        get
        {
            if (_poolSize == 0)
            {
                // 获取环境变量
                var poolSize = Environment.GetEnvironmentVariable("HttpClientPoolSize");
                if (!string.IsNullOrEmpty(poolSize) && int.TryParse(poolSize, out var size))
                {
                    _poolSize = size;
                }
                else
                {
                    _poolSize = Environment.ProcessorCount;
                }

                if (_poolSize < 1)
                {
                    _poolSize = 2;
                }
            }

            return _poolSize;
        }
    }

    private static readonly ConcurrentDictionary<string, Lazy<List<HttpClient>>> HttpClientPool = new();

    /// <summary>
    /// 高并发下有问题
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    [Obsolete]
    public static HttpClient GetHttpClient(string key)
    {
        return HttpClientPool.GetOrAdd(key, k => new Lazy<List<HttpClient>>(() =>
        {
            var clients = new List<HttpClient>(PoolSize);

            for (var i = 0; i < PoolSize; i++)
            {
                clients.Add(new HttpClient(new SocketsHttpHandler
                {
                    PooledConnectionLifetime = TimeSpan.FromMinutes(30),
                    PooledConnectionIdleTimeout = TimeSpan.FromMinutes(30),
                    EnableMultipleHttp2Connections = true,
                    // 连接超时5分钟
                    ConnectTimeout = TimeSpan.FromMinutes(5),
                    MaxAutomaticRedirections = 3,
                    AllowAutoRedirect = true,
                    Expect100ContinueTimeout = TimeSpan.FromMinutes(30),
                })
                {
                    Timeout = TimeSpan.FromMinutes(30),
                    DefaultRequestHeaders =
                    {
                        { "User-Agent", "yxai" },
                    }
                });
            }

            return clients;
        })).Value[new Random().Next(0, PoolSize)];
    }
}