using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EonaCat.Logger.EonaCatCoreLogger
{
    public class DiscordLogger : ILogger, IDisposable
    {
        private readonly string _categoryName;
        private readonly DiscordLoggerOptions _options;
        private readonly LoggerScopedContext _context = new LoggerScopedContext();

        private readonly HttpClient _httpClient = new HttpClient();
        private readonly SemaphoreSlim _flushLock = new SemaphoreSlim(1, 1);
        private readonly ConcurrentQueue<string> _messageQueue = new ConcurrentQueue<string>();

        private bool _flushLoopStarted = false;
        private CancellationTokenSource _cts;
        private Task _flushTask;

        public bool IncludeCorrelationId { get; set; }
        public event EventHandler<Exception> OnException;

        public DiscordLogger(string categoryName, DiscordLoggerOptions options)
        {
            _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName));
            _options = options ?? throw new ArgumentNullException(nameof(options));
            IncludeCorrelationId = options.IncludeCorrelationId;

            // Start flush loop once
            if (!_flushLoopStarted)
            {
                _flushLoopStarted = true;
                _cts = new CancellationTokenSource();
                _flushTask = Task.Run(() => FlushLoopAsync(_cts.Token));
            }
        }

        public IDisposable BeginScope<TState>(TState state) => null;
        public bool IsEnabled(LogLevel logLevel) => _options.IsEnabled;

        public void SetContext(string key, string value) => _context.Set(key, value);
        public void ClearContext() => _context.Clear();
        public string GetContext(string key) => _context.Get(key);

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
            Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel) || formatter == null)
            {
                return;
            }

            if (IncludeCorrelationId)
            {
                var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
                _context.Set("CorrelationId", correlationId);
            }

            var message = formatter(state, exception);
            var logParts = new List<string>
            {
                $"**[{DateTime.UtcNow:u}]**",
                $"**[{logLevel}]**",
                $"**[{_categoryName}]**",
                $"Message: {message}"
            };

            foreach (var kvp in _context.GetAll())
            {
                logParts.Add($"`{kvp.Key}`: {kvp.Value}");
            }

            if (exception != null)
            {
                logParts.Add($"Exception: {exception}");
            }

            // Limit queue size to prevent memory growth
            if (_messageQueue.Count < 1000)
            {
                _messageQueue.Enqueue(string.Join("\n", logParts));
            }
            else
            {
                OnException?.Invoke(this, new Exception("DiscordLogger queue overflow"));
            }
        }

        private async Task FlushLoopAsync(CancellationToken token)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    await Task.Delay(TimeSpan.FromSeconds(_options.FlushIntervalSeconds), token)
                              .ConfigureAwait(false);
                    await FlushBufferAsync(token).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                // Expected on cancel
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        private async Task FlushBufferAsync(CancellationToken token)
        {
            if (!await _flushLock.WaitAsync(0, token).ConfigureAwait(false))
            {
                return;
            }

            try
            {
                while (_messageQueue.TryDequeue(out var message))
                {
                    try
                    {
                        var payload = new { content = message };
                        using var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");
                        var response = await _httpClient.PostAsync(_options.WebhookUrl, content, token)
                                                        .ConfigureAwait(false);

                        if (!response.IsSuccessStatusCode)
                        {
                            var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            OnException?.Invoke(this, new Exception($"Discord webhook failed: {response.StatusCode} {error}"));
                        }
                    }
                    catch (Exception ex)
                    {
                        OnException?.Invoke(this, ex);
                    }
                }
            }
            finally
            {
                _flushLock.Release();
            }
        }

        public void Dispose()
        {
            if (_cts != null && !_cts.IsCancellationRequested)
            {
                _cts.Cancel();
                try
                {
                    _flushTask?.Wait();
                }
                catch (AggregateException ae)
                {
                    ae.Handle(e => e is OperationCanceledException);
                }
                _cts.Dispose();
                _cts = null;
            }
        }

        public void Shutdown()
        {
            _cts?.Cancel();
            try
            {
                _flushTask?.Wait();
            }
            catch (AggregateException ae)
            {
                ae.Handle(e => e is OperationCanceledException);
            }
            _flushLock.Dispose();
            _httpClient.Dispose();
        }
    }
}
