using EonaCat.Json;
using EonaCat.LogStack.Core;
using System;
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 ZabbixFlow : FlowBase
    {
        private readonly int _batchSize;
        private const int ChannelCapacity = 4096;

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

        private readonly string _host;
        private readonly int _port;
        private TcpClient? _tcpClient;
        private NetworkStream? _stream;
        private readonly BackpressureStrategy _backpressureStrategy;
        private readonly string _zabbixHostName;
        private readonly string _zabbixKey;

        public ZabbixFlow(
            string host,
            int port = 10051,
            string zabbixHostName = null,
            string zabbixKey = "log_event",
            int batchSize = 1,
            LogLevel minimumLevel = LogLevel.Trace,
            BackpressureStrategy backpressureStrategy = BackpressureStrategy.DropOldest)
            : base($"Zabbix:{host}:{port}", minimumLevel)
        {
            _host = host ?? throw new ArgumentNullException(nameof(host));
            _port = port;
            _backpressureStrategy = backpressureStrategy;
            _zabbixHostName = zabbixHostName ?? Environment.MachineName;
            _zabbixKey = zabbixKey ?? "log_event";

            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
            };

            _batchSize = batchSize <= 0 ? 1 : batchSize;
            _channel = Channel.CreateBounded<LogEvent>(channelOptions);
            _cts = new CancellationTokenSource();
            _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);

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    await EnsureConnectedAsync(cancellationToken);

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

                        if (batch.Count >= _batchSize || _channel.Reader.Count == 0)
                        {
                            await SendBatchAsync(batch, cancellationToken);
                            batch.Clear();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine($"ZabbixFlow error: {ex.Message}");
                    await Task.Delay(1000, cancellationToken);
                    _tcpClient?.Dispose();
                    _tcpClient = null;
                }
            }
        }

        private async Task EnsureConnectedAsync(CancellationToken cancellationToken)
        {
            if (_tcpClient != null && _tcpClient.Connected)
            {
                return;
            }

            _tcpClient?.Dispose();
            _tcpClient = new TcpClient();
            await _tcpClient.ConnectAsync(_host, _port);
            _stream = _tcpClient.GetStream();
        }

        private async Task SendBatchAsync(List<LogEvent> batch, CancellationToken cancellationToken)
        {
            if (_stream == null || batch.Count == 0)
            {
                return;
            }

            foreach (var logEvent in batch)
            {
                var payload = new
                {
                    request = "sender data",
                    data = new[]
                    {
                        new {
                            host = _zabbixHostName,
                            key = _zabbixKey,
                            value = FormatLogEvent(logEvent)
                        }
                    }
                };

                string json = JsonHelper.ToJson(payload);
                byte[] jsonBytes = Encoding.UTF8.GetBytes(json);

                // Zabbix protocol header
                byte[] header = new byte[13]; // "ZBXD\1" + 8 bytes length
                header[0] = (byte)'Z';
                header[1] = (byte)'B';
                header[2] = (byte)'X';
                header[3] = (byte)'D';
                header[4] = 1;

                long length = jsonBytes.Length;
                for (int i = 0; i < 8; i++)
                {
                    header[5 + i] = (byte)(length >> (8 * i) & 0xFF);
                }

                await _stream.WriteAsync(header, 0, header.Length, cancellationToken);
                await _stream.WriteAsync(jsonBytes, 0, jsonBytes.Length, cancellationToken);
                await _stream.FlushAsync(cancellationToken);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private string FormatLogEvent(LogEvent logEvent)
        {
            var dt = LogEvent.GetDateTime(logEvent.Timestamp);
            string ts = dt.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string category = string.IsNullOrEmpty(logEvent.Category) ? "ZabbixFlow" : logEvent.Category;
            return $"{ts} [{logEvent.Level}] {category}: {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 { }

            _stream?.Dispose();
            _tcpClient?.Dispose();
            _cts.Dispose();

            await base.DisposeAsync();
        }
    }
}
