using EonaCat.LogStack.Core;
using System;
using System.Collections.Generic;
using System.Threading;
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.

    /// <summary>
    /// A flow that buffers log events and flushes them on a schedule or when a size threshold is reached.
    /// Useful for improving performance by batching writes to an underlying flow.
    /// </summary>
    public sealed class BufferedFlow : FlowBase
    {
        private readonly IFlow _innerFlow;
        private readonly int _bufferSize;
        private readonly TimeSpan _flushInterval;
        private readonly List<LogEvent> _buffer;
        private readonly SemaphoreSlim _semaphore;
        private readonly Timer _flushTimer;
        private readonly object _bufferLock = new();
        private bool _disposed;

        public BufferedFlow(
            IFlow innerFlow,
            int bufferSize = 1000,
            int flushIntervalMs = 5000,
            LogLevel minimumLevel = LogLevel.Trace)
            : base(innerFlow?.Name + "_Buffered" ?? "BufferedFlow", minimumLevel)
        {
            _innerFlow = innerFlow ?? throw new ArgumentNullException(nameof(innerFlow));
            _bufferSize = bufferSize > 0 ? bufferSize : throw new ArgumentException("Buffer size must be greater than 0", nameof(bufferSize));
            _flushInterval = TimeSpan.FromMilliseconds(flushIntervalMs > 0 ? flushIntervalMs : 5000);
            _buffer = new List<LogEvent>(_bufferSize);
            _semaphore = new SemaphoreSlim(1, 1);
            _flushTimer = new Timer(FlushTimerCallback, null, _flushInterval, _flushInterval);
        }

        public override async Task<WriteResult> BlastAsync(LogEvent logEvent, CancellationToken cancellationToken = default)
        {
            if (!IsEnabled || !IsLogLevelEnabled(logEvent))
            {
                return WriteResult.LevelFiltered;
            }

            await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
            try
            {
                lock (_bufferLock)
                {
                    _buffer.Add(logEvent);
                    Interlocked.Increment(ref BlastedCount);

                    if (_buffer.Count >= _bufferSize)
                    {
                        // Return a fire-and-forget task to flush
                        _ = FlushInternalAsync(cancellationToken);
                    }
                }

                return WriteResult.Success;
            }
            finally
            {
                _semaphore.Release();
            }
        }

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

            await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
            try
            {
                lock (_bufferLock)
                {
                    foreach (var logEvent in logEvents.Span)
                    {
                        if (IsLogLevelEnabled(logEvent))
                        {
                            _buffer.Add(logEvent);
                            Interlocked.Increment(ref BlastedCount);
                        }
                    }

                    if (_buffer.Count >= _bufferSize)
                    {
                        _ = FlushInternalAsync(cancellationToken);
                    }
                }

                return WriteResult.Success;
            }
            finally
            {
                _semaphore.Release();
            }
        }

        public override async Task FlushAsync(CancellationToken cancellationToken = default)
        {
            await FlushInternalAsync(cancellationToken).ConfigureAwait(false);
        }

        private async Task FlushInternalAsync(CancellationToken cancellationToken)
        {
            List<LogEvent> eventsToFlush;
            lock (_bufferLock)
            {
                if (_buffer.Count == 0)
                {
                    return;
                }

                eventsToFlush = new List<LogEvent>(_buffer);
                _buffer.Clear();
            }

            if (eventsToFlush.Count > 0)
            {
                try
                {
                    await _innerFlow.BlastBatchAsync(eventsToFlush.ToArray(), cancellationToken).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Interlocked.Add(ref DroppedCount, eventsToFlush.Count);
                    System.Diagnostics.Debug.WriteLine($"BufferedFlow flush error: {ex.Message}");
                }
            }
        }

        private void FlushTimerCallback(object? state)
        {
            if (!_disposed)
            {
                _ = FlushInternalAsync(CancellationToken.None);
            }
        }

        public override async ValueTask DisposeAsync()
        {
            _disposed = true;
            _flushTimer?.Dispose();
            await FlushAsync(default).ConfigureAwait(false);
            _semaphore?.Dispose();
            await _innerFlow.DisposeAsync().ConfigureAwait(false);
            await base.DisposeAsync().ConfigureAwait(false);
        }
    }
}
