using EonaCat.Json;
using EonaCat.LogStack.Core;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

// 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.

namespace EonaCat.LogStack.Flows
{
    public sealed class SplunkFlow : 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 _splunkUrl;
        private readonly string _token;
        private readonly string _sourcetype;
        private readonly string _hostName;

        private readonly BackpressureStrategy _backpressureStrategy;
        private readonly HttpClient _httpClient;

        public SplunkFlow(
            string splunkUrl,
            string token,
            string sourcetype = "splunk_logs",
            string hostName = null,
            int batchSize = 1,
            LogLevel minimumLevel = LogLevel.Trace,
            BackpressureStrategy backpressureStrategy = BackpressureStrategy.DropOldest)
            : base($"Splunk:{splunkUrl}", minimumLevel)
        {
            _splunkUrl = splunkUrl ?? throw new ArgumentNullException(nameof(splunkUrl));
            _token = token ?? throw new ArgumentNullException(nameof(token));
            _sourcetype = sourcetype;
            _hostName = hostName ?? Environment.MachineName;
            _backpressureStrategy = backpressureStrategy;

            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();
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Splunk {_token}");

            _senderTask = Task.Run(() => ProcessLogEventsAsync(_cts.Token));
        }

        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 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($"SplunkFlow error: {ex.Message}");
                    await Task.Delay(1000, cancellationToken);
                }
            }
        }

        private async Task SendBatchAsync(List<LogEvent> batch, CancellationToken cancellationToken)
        {
            foreach (var logEvent in batch)
            {
                var splunkEvent = new
                {
                    time = ToUnixTimeSeconds(LogEvent.GetDateTime(logEvent.Timestamp)),
                    host = _hostName,
                    sourcetype = _sourcetype,
                    @event = new
                    {
                        level = logEvent.Level.ToString(),
                        category = logEvent.Category,
                        message = logEvent.Message
                    }
                };

                string json = JsonHelper.ToJson(splunkEvent);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                try
                {
                    await _httpClient.PostAsync(_splunkUrl, content, cancellationToken);
                }
                catch
                {
                    // ignore errors
                }
            }
        }

        // Helper to convert DateTime to Unix timestamp (works in .NET 4.8.x)
        private static double ToUnixTimeSeconds(DateTime dt)
        {
            var utc = dt.ToUniversalTime();
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (utc - epoch).TotalSeconds;
        }

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

            _httpClient.Dispose();
            _cts.Dispose();

            await base.DisposeAsync();
        }
    }
}
