using System;
using System.Diagnostics;
using UnityEngine;

namespace Combo.Core
{
    public static class Log
    {
        public static void I(object message)
        {
            UnityEngine.Debug.Log($"[ComboSDK] {Tag}: " + ParseMessage(message));
        }

        public static void D(object message)
        {
            UnityEngine.Debug.Log($"[ComboSDK] {Tag}: " + ParseMessage(message));
        }

        public static void E(object message)
        {
            UnityEngine.Debug.LogError($"[ComboSDK] {Tag}: " + ParseMessage(message));
        }

        public static void W(object message)
        {
            UnityEngine.Debug.LogWarning($"[ComboSDK] {Tag}: " + ParseMessage(message));
        }

        static string Tag {
            get {
                var type = new StackTrace()?.GetFrame(2)?.GetMethod()?.ReflectedType;
                while ((type?.Name?.Contains("__") ?? false) || (type?.Name?.Contains("`") ?? false) || (type?.Name?.Contains("<") ?? false) || (type?.Name?.Contains(">") ?? false))
                    type = type?.ReflectedType ?? null;
                return type?.Name ?? "";
            }
        }

        /// <summary>
        /// 平台自动切换 JSON 序列化方式：
        /// 非 WebGL：Newtonsoft.Json
        /// WebGL：LitJson
        /// </summary>
        static string ParseMessage(object message)
        {
            if (message == null)
                return "null";

            // 原始类型或字符串直接输出
            if (message.GetType().IsPrimitive || message is string)
            {
                return message.ToString();
            }

            // --------- 非 WebGL：使用 Newtonsoft.Json ---------
#if !UNITY_WEBGL
            try
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(message);
            }
            catch
            {
                return message.ToString();
            }

            // --------- WebGL：使用 LitJson ---------
#else
            try
            {
                return Seayoo.LitJson.JsonMapper.ToJson(message);
            }
            catch
            {
                return message.ToString();
            }
#endif
        }
    }
}