using EonaCat.LogStack.Core;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace EonaCat.LogStack.Flows
{
    // 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.

    public sealed class SyslogUdpFlow : FlowBase
    {
        private readonly int _batchSize;
        private const int ChannelCapacity = 4096;
        private const int MaxUdpPacketSize = 4096;

        private readonly Channel<LogEvent> _channel;
        private readonly Task _senderTask;
        private readonly CancellationTokenSource _cts;

        private readonly string _host;
        private readonly int _port;
        private UdpClient? _udpClient;
        private readonly BackpressureStrategy _backpressureStrategy;

        public SyslogUdpFlow(
            string host,
            int port = 514,
            int batchSize = 1,
            LogLevel minimumLevel = LogLevel.Trace,
            BackpressureStrategy backpressureStrategy = BackpressureStrategy.DropOldest)
            : base($"SyslogUDP:{host}:{port}", minimumLevel)
        {
            _host = host ?? throw new ArgumentNullException(nameof(host));
            _port = port;
            _backpressureStrategy = backpressureStrategy;

            _batchSize = batchSize <= 0 ? 1 : batchSize;

            var channelOptions = new BoundedChannelOptions(ChannelCapacity)
            {
                FullMode = backpressureStrategy switch
                {
                    BackpressureStrategy.Wait => BoundedChannelFullMode.Wait,
                    BackpressureStrategy.DropNewest => BoundedChannelFullMode.DropWrite,
                    BackpressureStrategy.DropOldest => BoundedChannelFullMode.DropOldest,
                    _ => BoundedChannelFullMode.Wait
                },
                SingleReader = true,
                SingleWriter = false
            };

            _channel = Channel.CreateBounded<LogEvent>(channelOptions);
            _cts = new CancellationTokenSource();
            _udpClient = new UdpClient();
            _senderTask = Task.Run(() => ProcessLogEventsAsync(_cts.Token));
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public override Task<WriteResult> BlastAsync(LogEvent logEvent, CancellationToken cancellationToken = default)
        {
            if (!IsEnabled || !IsLogLevelEnabled(logEvent))
            {
                return Task.FromResult(WriteResult.LevelFiltered);
            }

            if (_channel.Writer.TryWrite(logEvent))
            {
                Interlocked.Increment(ref BlastedCount);
                return Task.FromResult(WriteResult.Success);
            }

            Interlocked.Increment(ref DroppedCount);
            return Task.FromResult(WriteResult.Dropped);
        }

        public override async Task<WriteResult> BlastBatchAsync(ReadOnlyMemory<LogEvent> logEvents, CancellationToken cancellationToken = default)
        {
            if (!IsEnabled)
            {
                return WriteResult.FlowDisabled;
            }

            var result = WriteResult.Success;
            foreach (var logEvent in logEvents.Span)
            {
                if (!IsLogLevelEnabled(logEvent))
                {
                    continue;
                }

                if (_channel.Writer.TryWrite(logEvent))
                {
                    Interlocked.Increment(ref BlastedCount);
                }
                else
                {
                    Interlocked.Increment(ref DroppedCount);
                    result = WriteResult.Dropped;
                }
            }

            return result;
        }

        private async Task ProcessLogEventsAsync(CancellationToken cancellationToken)
        {
            var batch = new List<LogEvent>(_batchSize);
            var sb = new StringBuilder(8192);

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    await foreach (var logEvent in _channel.Reader.ReadAllAsync(cancellationToken))
                    {
                        batch.Add(logEvent);

                        if (batch.Count >= _batchSize || _channel.Reader.Count == 0)
                        {
                            await SendBatchAsync(batch, sb, cancellationToken);
                            batch.Clear();
                            sb.Clear();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"SyslogUdpFlow error: {ex.Message}");
                    await Task.Delay(500, cancellationToken);
                }
            }
        }

        private async Task SendBatchAsync(List<LogEvent> batch, StringBuilder sb, CancellationToken cancellationToken)
        {
            foreach (var logEvent in batch)
            {
                FormatSyslogEvent(logEvent, sb);
                sb.AppendLine();
            }

            if (_udpClient == null)
            {
                return;
            }

            var data = Encoding.UTF8.GetBytes(sb.ToString());

            if (data.Length <= MaxUdpPacketSize)
            {
                try
                {
                    await _udpClient.SendAsync(data, data.Length, _host, _port);
                }
                catch
                {
                    // UDP send errors are ignored
                }
            }
            else
            {
                await SendUdpInChunksAsync(data, MaxUdpPacketSize, cancellationToken);
            }
        }

        private async Task SendUdpInChunksAsync(byte[] data, int chunkSize, CancellationToken cancellationToken)
        {
            int offset = 0;
            byte[] buffer = ArrayPool<byte>.Shared.Rent(chunkSize);

            try
            {
                while (offset < data.Length)
                {
                    int size = Math.Min(chunkSize, data.Length - offset);
                    Buffer.BlockCopy(data, offset, buffer, 0, size);
                    await _udpClient.SendAsync(buffer, size, _host, _port);
                    offset += size;
                }
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void FormatSyslogEvent(LogEvent logEvent, StringBuilder sb)
        {
            int severity = logEvent.Level switch
            {
                LogLevel.Trace => 7,
                LogLevel.Debug => 7,
                LogLevel.Information => 6,
                LogLevel.Warning => 4,
                LogLevel.Error => 3,
                LogLevel.Critical => 2,
                _ => 6
            };
            int facility = 1;
            int pri = facility * 8 + severity;

            var dt = LogEvent.GetDateTime(logEvent.Timestamp);
            sb.Append('<').Append(pri).Append('>');
            sb.Append(dt.ToString("MMM dd HH:mm:ss"));
            sb.Append(" ").Append(Environment.MachineName);
            sb.Append(" ").Append(string.IsNullOrEmpty(logEvent.Category) ? "SyslogUdpFlow" : logEvent.Category);
            sb.Append(": ").Append(logEvent.Message);
        }

        public override async Task FlushAsync(CancellationToken cancellationToken = default)
        {
            _channel.Writer.Complete();
            try { await _senderTask.ConfigureAwait(false); } catch { }
        }

        public override async ValueTask DisposeAsync()
        {
            IsEnabled = false;
            _channel.Writer.Complete();
            _cts.Cancel();

            try { await _senderTask.ConfigureAwait(false); } catch { }

            _udpClient?.Dispose();
            _cts.Dispose();

            await base.DisposeAsync();
        }
    }
}
