using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace EonaCat.Logger.EonaCatCoreLogger
{
    public sealed class UdpLogger : ILogger, IDisposable
    {
        // This file is part of the EonaCat project(s) which is released under the Apache License.
        // See the LICENSE file or go to https://EonaCat.com/License for full license details.

        private readonly string _categoryName;
        private readonly UdpLoggerOptions _options;
        private readonly LoggerScopedContext _context = new();
        private readonly Channel<string> _logChannel;
        private readonly UdpClient _udpClient;
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private readonly Task _processingTask;

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

        public UdpLogger(string categoryName, UdpLoggerOptions options)
        {
            _categoryName = categoryName;
            _options = options;
            IncludeCorrelationId = options.IncludeCorrelationId;

            _udpClient = new UdpClient();

            // Bounded channel to avoid unbounded memory growth
            _logChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(1000)
            {
                FullMode = BoundedChannelFullMode.DropOldest,
                SingleReader = true,
                SingleWriter = false
            });

            _processingTask = Task.Run(() => ProcessLogQueueAsync(_cts.Token));
        }

        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 IDisposable BeginScope<TState>(TState state) => _context.BeginScope(state);
        public bool IsEnabled(LogLevel logLevel) => _options.IsEnabled;

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

            try
            {
                string message = formatter(state, exception);

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

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

                var contextData = _context.GetAll();
                if (contextData.Count > 0)
                {
                    logParts.Add("Context:");
                    foreach (var kvp in contextData)
                    {
                        logParts.Add($"{kvp.Key}: {kvp.Value}");
                    }
                }

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

                string fullMessage = string.Join(" | ", logParts);

                // Non-blocking, drop oldest if full
                _logChannel.Writer.TryWrite(fullMessage);
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        private async Task ProcessLogQueueAsync(CancellationToken token)
        {
            try
            {
                await foreach (var message in _logChannel.Reader.ReadAllAsync(token))
                {
                    try
                    {
                        byte[] bytes = Encoding.UTF8.GetBytes(message);
                        await _udpClient.SendAsync(bytes, bytes.Length, _options.Host, _options.Port);
                    }
                    catch (Exception ex)
                    {
                        OnException?.Invoke(this, ex);
                    }
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        public void Dispose()
        {
            _cts.Cancel();
            _logChannel.Writer.Complete();

            try
            {
                _processingTask.Wait();
            }
            catch { /* ignore */ }

            _udpClient.Dispose();
            _cts.Dispose();
        }
    }
}
