using System.Linq;

// 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.Logger.EonaCatCoreLogger
{
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;

    public class ElasticSearchLogger : ILogger
    {
        private readonly string _categoryName;
        private readonly ElasticSearchLoggerOptions _options;
        private static readonly HttpClient _httpClient = new HttpClient();
        private static readonly List<string> _buffer = new List<string>();
        private static readonly object _lock = new object();
        private static bool _flushLoopStarted = false;
        public event EventHandler<Exception> OnException;
        public event EventHandler<string> OnInvalidStatusCode;
        private readonly LoggerScopedContext _context = new();
        public bool IncludeCorrelationId { get; set; }

        public ElasticSearchLogger(string categoryName, ElasticSearchLoggerOptions options)
        {
            _categoryName = categoryName;
            _options = options;
            IncludeCorrelationId = options.IncludeCorrelationId;

            if (!_flushLoopStarted)
            {
                _flushLoopStarted = true;
                Task.Run(FlushLoopAsync);
            }
        }

        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) => null;
        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 (!_options.IsEnabled || formatter == null)
            {
                return;
            }

            // Get correlation ID from context or generate new one
            if (IncludeCorrelationId)
            {
                var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
                _context.Set("CorrelationId", correlationId);
            }

            // Prepare the log entry
            var logDoc = new
            {
                timestamp = DateTime.UtcNow,
                level = logLevel.ToString(),
                category = _categoryName,
                message = formatter(state, exception),
                exception = exception?.ToString(),
                eventId = eventId.Id,
                customContext = _context.GetAll() 
            };

            // Serialize log to JSON
            string json = JsonSerializer.Serialize(logDoc);

            // Add to the buffer
            lock (_lock)
            {
                _buffer.Add(json);
                if (_buffer.Count >= _options.RetryBufferSize)
                {
                    _ = FlushBufferAsync();
                }
            }
        }

        private async Task FlushLoopAsync()
        {
            while (true)
            {
                await Task.Delay(TimeSpan.FromSeconds(_options.FlushIntervalSeconds));
                await FlushBufferAsync();
            }
        }

        private async Task FlushBufferAsync()
        {
            List<string> toSend;
            lock (_lock)
            {
                if (_buffer.Count == 0) return;
                toSend = new List<string>(_buffer);
                _buffer.Clear();
            }

            // Elasticsearch URL with dynamic index
            string indexName = $"{_options.IndexName}-{DateTime.UtcNow:yyyy.MM.dd}";
            string url = $"{_options.Uri.TrimEnd('/')}/{(_options.UseBulkInsert ? "_bulk" : indexName + "/_doc")}";

            var request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Headers.Accept.ParseAdd("application/json");

            // Add authentication headers if configured
            if (!string.IsNullOrWhiteSpace(_options.Username))
            {
                var authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_options.Username}:{_options.Password}"));
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);
            }

            // Add custom headers (static ones)
            foreach (var header in _options.CustomHeaders)
            {
                request.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            // Add template headers (dynamic ones based on log data)
            var dynamicHeaders = new Dictionary<string, string>
            {
                { "index", _options.IndexName },
                { "date", DateTime.UtcNow.ToString("yyyy-MM-dd") },
                { "timestamp", DateTime.UtcNow.ToString("o") },
            };

            foreach (var header in _options.TemplateHeaders)
            {
                var value = ReplaceTemplate(header.Value, dynamicHeaders);
                request.Headers.TryAddWithoutValidation(header.Key, value);
            }

            // Add context headers (correlationId, custom context)
            foreach (var kv in _context.GetAll())
            {
                request.Headers.TryAddWithoutValidation($"X-Context-{kv.Key}", kv.Value);
            }

            // Prepare the content for the request
            request.Content = new StringContent(
                _options.UseBulkInsert
                    ? string.Join("\n", toSend.Select(d => $"{{\"index\":{{}}}}\n{d}")) + "\n"
                    : string.Join("\n", toSend),
                Encoding.UTF8,
                "application/json"
            );

            try
            {
                var response = await _httpClient.SendAsync(request);
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    OnInvalidStatusCode?.Invoke(this, $"ElasticSearch request failed: {response.StatusCode}, {errorContent}");
                }
            }
            catch (Exception exception)
            {
                OnException?.Invoke(this, exception);
            }
        }

        private static string ReplaceTemplate(string template, Dictionary<string, string> values)
        {
            foreach (var kv in values)
            {
                template = template.Replace($"{{{kv.Key}}}", kv.Value);
            }
            return template;
        }
    }
}
