using System;
using System.IO;

namespace AxCopilot.Services;

public static class LogService
{
	private static readonly string LogDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AxCopilot", "logs");

	private static readonly object _lock = new object();

	private const int RetentionDays = 14;

	private static bool _purged;

	private static string LogFile => Path.Combine(LogDir, $"app-{DateTime.Now:yyyy-MM-dd}.log");

	public static LogLevel MinLevel { get; set; } = LogLevel.Info;

	public static void Debug(string msg)
	{
		Write(LogLevel.Debug, msg);
	}

	public static void Info(string msg)
	{
		Write(LogLevel.Info, msg);
	}

	public static void Warn(string msg)
	{
		Write(LogLevel.Warn, msg);
	}

	public static void Error(string msg)
	{
		Write(LogLevel.Error, msg);
	}

	private static void Write(LogLevel level, string msg)
	{
		if (level < MinLevel)
		{
			return;
		}
		try
		{
			Directory.CreateDirectory(LogDir);
			string text = $"[{DateTime.Now:HH:mm:ss.fff}] [{level,-5}] {msg}";
			lock (_lock)
			{
				File.AppendAllText(LogFile, text + Environment.NewLine);
			}
			if (!_purged)
			{
				_purged = true;
				PurgeOldLogs();
			}
		}
		catch
		{
		}
	}

	private static void PurgeOldLogs()
	{
		try
		{
			DateTime dateTime = DateTime.Now.AddDays(-14.0);
			string[] files = Directory.GetFiles(LogDir, "app-*.log");
			foreach (string path in files)
			{
				if (File.GetCreationTime(path) < dateTime)
				{
					File.Delete(path);
				}
			}
		}
		catch
		{
		}
	}
}
