using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace GTPCorrgir
{
    public class ErrorLogger
    {
        private const string ERROR_FOLDER = "ErrorLogs";
        private const int MAX_LOG_FILES = 5;
        private readonly string logPath;
        private readonly object lockObj = new object();

        public ErrorLogger()
        {
            logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ERROR_FOLDER);
            EnsureLogFolderExists();
            CleanupOldLogs();
        }

        private void EnsureLogFolderExists()
        {
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
        }

        private void CleanupOldLogs()
        {
            try
            {
                var files = Directory.GetFiles(logPath, "*.json")
                    .OrderByDescending(f => File.GetLastWriteTime(f));

                int count = 0;
                foreach (var file in files)
                {
                    count++;
                    if (count > MAX_LOG_FILES)
                    {
                        File.Delete(file);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error cleaning up logs: {ex.Message}");
            }
        }

        public async Task LogErrorAsync(Exception ex, string context = "")
        {
            var errorInfo = new
            {
                Timestamp = DateTime.Now,
                Context = context,
                Exception = new
                {
                    Message = ex.Message,
                    StackTrace = ex.StackTrace,
                    Source = ex.Source,
                    TargetSite = ex.TargetSite?.ToString(),
                    InnerException = ex.InnerException?.Message
                },
                SystemInfo = new
                {
                    OSVersion = Environment.OSVersion.ToString(),
                    MachineName = Environment.MachineName,
                    ProcessorCount = Environment.ProcessorCount,
                    WorkingSet = Environment.WorkingSet,
                    CurrentDirectory = Environment.CurrentDirectory
                }
            };

            string filename = $"error_log_{DateTime.Now:yyyyMMdd_HHmmss}.json";
            string fullPath = Path.Combine(logPath, filename);

            try
            {
                string json = JsonConvert.SerializeObject(errorInfo, Formatting.Indented);
                await File.WriteAllTextAsync(fullPath, json);

                // También escribir al log de debug
                Debug.WriteLine($"Error logged: {context} - {ex.Message}");
            }
            catch (Exception logEx)
            {
                Debug.WriteLine($"Error writing to error log: {logEx.Message}");
            }
        }

        public async Task<string> GetErrorSummaryAsync()
        {
            var summary = new StringBuilder();
            try
            {
                var files = Directory.GetFiles(logPath, "*.json")
                    .OrderByDescending(f => File.GetLastWriteTime(f))
                    .Take(5);

                foreach (var file in files)
                {
                    string content = await File.ReadAllTextAsync(file);
                    var error = JsonConvert.DeserializeObject<dynamic>(content);
                    summary.AppendLine($"Time: {error.Timestamp}");
                    summary.AppendLine($"Context: {error.Context}");
                    summary.AppendLine($"Error: {error.Exception.Message}");
                    summary.AppendLine("-------------------");
                }
            }
            catch (Exception ex)
            {
                summary.AppendLine($"Error reading error logs: {ex.Message}");
            }

            return summary.ToString();
        }
    }
}