using System;
using UnityEngine;

namespace MJGameSDK
{
    public enum MJGameLogLevel
    {
        Debug = 0,
        Info = 1,
        Warn = 2,
        Error = 3,
        None = 4
    }

    public static class MJGameLogger
    {
        private static MJGameLogLevel _level = MJGameLogLevel.Debug;
        private static bool _fileLogEnabled;
        private static string _logFilePath;

        public static event Action<string, MJGameLogLevel> OnLog;

        public static void Initialize(MJGameLogLevel level, bool enableFileLog)
        {
            _level = level;
            _fileLogEnabled = enableFileLog;
            if (enableFileLog)
            {
                _logFilePath = System.IO.Path.Combine(Application.persistentDataPath, "mjgame_sdk.log");
            }
        }

        public static void Debug(string tag, string message) => Log(MJGameLogLevel.Debug, tag, message);
        public static void Info(string tag, string message) => Log(MJGameLogLevel.Info, tag, message);
        public static void Warn(string tag, string message) => Log(MJGameLogLevel.Warn, tag, message);
        public static void Error(string tag, string message) => Log(MJGameLogLevel.Error, tag, message);

        private static void Log(MJGameLogLevel level, string tag, string message)
        {
            if (level < _level) return;

            var requestId = MJGameHttpClient.CurrentRequestId ?? "-";
            var formatted = $"[{DateTime.Now:HH:mm:ss.fff}] [{level}] [{tag}] [req:{requestId}] {message}";

            switch (level)
            {
                case MJGameLogLevel.Debug:
                case MJGameLogLevel.Info:
                    UnityEngine.Debug.Log(formatted);
                    break;
                case MJGameLogLevel.Warn:
                    UnityEngine.Debug.LogWarning(formatted);
                    break;
                case MJGameLogLevel.Error:
                    UnityEngine.Debug.LogError(formatted);
                    break;
            }

            OnLog?.Invoke(formatted, level);

            if (_fileLogEnabled && !string.IsNullOrEmpty(_logFilePath))
            {
                try
                {
                    System.IO.File.AppendAllText(_logFilePath, formatted + Environment.NewLine);
                }
                catch { /* ignore file write errors */ }
            }
        }
    }
}
