using System.Globalization;

namespace Metin2Launcher.Logging;

/// <summary>
/// Hand-rolled logger: writes to stdout and a rolling (well, appending) log file.
/// Thread-safe via a lock. Intentionally simple — no Serilog/NLog for MVP.
/// </summary>
public static class Log
{
    private static readonly object Gate = new();
    private static string? _logFilePath;

    public static string LogFilePath
    {
        get
        {
            if (_logFilePath is null)
            {
                _logFilePath = DefaultLogFilePath();
            }
            return _logFilePath;
        }
    }

    public static void SetLogFilePath(string path)
    {
        lock (Gate)
        {
            _logFilePath = path;
            var dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir))
                Directory.CreateDirectory(dir);
        }
    }

    public static void Info(string message)  => Write("INFO ", message);
    public static void Warn(string message)  => Write("WARN ", message);
    public static void Error(string message) => Write("ERROR", message);

    public static void Error(string message, Exception ex)
        => Write("ERROR", message + " :: " + ex);

    private static void Write(string level, string message)
    {
        var line = string.Format(
            CultureInfo.InvariantCulture,
            "{0:yyyy-MM-dd HH:mm:ss.fff} {1} {2}",
            DateTime.UtcNow, level, message);

        lock (Gate)
        {
            Console.WriteLine(line);
            try
            {
                var path = LogFilePath;
                var dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir))
                    Directory.CreateDirectory(dir);
                File.AppendAllText(path, line + Environment.NewLine);
            }
            catch
            {
                // Deliberately swallow — logging must never take the process down.
            }
        }
    }

    private static string DefaultLogFilePath()
    {
        string baseDir;
        if (OperatingSystem.IsWindows())
        {
            baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        }
        else
        {
            var xdg = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
            if (string.IsNullOrEmpty(xdg))
            {
                xdg = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                    ".local", "share");
            }
            baseDir = xdg;
        }
        return Path.Combine(baseDir, "Metin2Launcher", "launcher.log");
    }
}
