using System.IO;

namespace AxCopilot.Services;

public enum LogLevel { Debug, Info, Warn, Error }

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

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

    private static readonly object _lock = new();

    private const int RetentionDays = 14; // 14일 이상 지난 로그 파일 자동 삭제
    private static bool _purged;

    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);
            var line = $"[{DateTime.Now:HH:mm:ss.fff}] [{level,-5}] {msg}";
            lock (_lock)
                File.AppendAllText(LogFile, line + Environment.NewLine);

            // 앱 세션 당 1회 오래된 로그 삭제
            if (!_purged) { _purged = true; PurgeOldLogs(); }
        }
        catch (Exception) { /* 로깅 실패는 무시 */ }
    }

    private static void PurgeOldLogs()
    {
        try
        {
            var cutoff = DateTime.Now.AddDays(-RetentionDays);
            foreach (var file in Directory.GetFiles(LogDir, "app-*.log"))
            {
                if (File.GetCreationTime(file) < cutoff)
                    File.Delete(file);
            }
        }
        catch (Exception) { }
    }
}
