using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
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 TcpLogger : ILogger, IDisposable
    {
        private readonly string _categoryName;
        private readonly TcpLoggerOptions _options;
        private readonly LoggerScopedContext _context = new();
        private readonly Channel<string> _logChannel;
        private readonly CancellationTokenSource _cts = new();
        private readonly Task _processingTask;

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

        public TcpLogger(string categoryName, TcpLoggerOptions options)
        {
            _categoryName = categoryName;
            _options = options;
            IncludeCorrelationId = options.IncludeCorrelationId;

            // Bounded channel to prevent 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 fullLog = string.Join(" | ", logParts);

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

        private async Task ProcessLogQueueAsync(CancellationToken token)
        {
            try
            {
                // Keep one TCP connection alive if possible
                using var client = new TcpClient();
                await client.ConnectAsync(_options.Host, _options.Port);

                using var stream = client.GetStream();
                using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };

                await foreach (var log in _logChannel.Reader.ReadAllAsync(token))
                {
                    try
                    {
                        await writer.WriteLineAsync(log);
                    }
                    catch (Exception e)
                    {
                        OnException?.Invoke(this, e);
                    }
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

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

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

            _cts.Dispose();
        }
    }
}
