using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace ViKPI.Internal
{
    internal static class Log
    {
        public const string Prefix = "[ViKPI] ";
        public static bool Verbose;
        private static readonly HashSet<string> Seen = new HashSet<string>();

        public static void Debug(string message)
        {
            if (Verbose) UnityEngine.Debug.Log(Prefix + message);
        }

        public static void Info(string message) => UnityEngine.Debug.Log(Prefix + message);

        public static void Warn(string message) => UnityEngine.Debug.LogWarning(Prefix + message);

        /// <summary>Warns once per key, so a bad call inside Update doesn't flood the console.</summary>
        public static void WarnOnce(string key, string message)
        {
            lock (Seen)
            {
                if (!Seen.Add(key)) return;
            }
            Warn(message);
        }

        public static void Error(string message) => UnityEngine.Debug.LogError(Prefix + message);
    }

    internal static class EventValidator
    {
        public const int MaxNameLength = 64;
        public const int MaxProps = 32;
        public const int MaxPropKeyLength = 64;
        public const int MaxPropValueLength = 512;

        private static readonly Regex NamePattern = new Regex(@"^\$?[A-Za-z0-9_.:\- ]+$", RegexOptions.CultureInvariant);

        public static bool IsValidName(string name, bool allowSystem)
        {
            if (string.IsNullOrEmpty(name) || name.Length > MaxNameLength) return false;
            if (!allowSystem && name[0] == '$') return false;
            return NamePattern.IsMatch(name) && name.Trim().Length > 0;
        }
    }

    /// <summary>
    /// Monotonic session clock in milliseconds. Unaffected by Time.timeScale and wall-clock changes,
    /// and readable from any thread (log callbacks arrive on worker threads).
    /// </summary>
    internal sealed class SessionClock
    {
        private readonly Stopwatch _watch = Stopwatch.StartNew();

        public long NowMs => _watch.ElapsedMilliseconds;
    }

    internal static class DeviceInfo
    {
        private const string DeviceIdKey = "vikpi.device_id";

        /// <summary>A random id for this install. Not derived from hardware; reset by reinstalling.</summary>
        public static string DeviceId()
        {
            var id = PlayerPrefs.GetString(DeviceIdKey, "");
            if (id.Length >= 8) return id;
            id = System.Guid.NewGuid().ToString("N");
            PlayerPrefs.SetString(DeviceIdKey, id);
            PlayerPrefs.Save();
            return id;
        }

        /// <summary>The stored install id, or null if none was ever created (nothing was collected).</summary>
        public static string PeekDeviceId()
        {
            var id = PlayerPrefs.GetString(DeviceIdKey, "");
            return id.Length >= 8 ? id : null;
        }

        /// <summary>Forgets the install id, so later data (if any) can't be linked to earlier sessions.</summary>
        public static void ResetDeviceId()
        {
            PlayerPrefs.DeleteKey(DeviceIdKey);
            PlayerPrefs.Save();
        }

        /// <summary>
        /// The app's identity for the server's app id check: Android package name, iOS/desktop
        /// bundle identifier, or the page origin on WebGL.
        /// </summary>
        public static string AppId()
        {
#if UNITY_WEBGL && !UNITY_EDITOR
            try
            {
                var u = new System.Uri(Application.absoluteURL);
                return u.GetLeftPart(System.UriPartial.Authority).ToLowerInvariant();
            }
            catch (System.Exception) { return ""; }
#else
            return Application.identifier ?? "";
#endif
        }

        public static string Platform()
        {
            switch (Application.platform)
            {
                case RuntimePlatform.Android: return "android";
                case RuntimePlatform.IPhonePlayer: return "ios";
                case RuntimePlatform.WebGLPlayer: return "webgl";
                case RuntimePlatform.WindowsPlayer: return "windows";
                case RuntimePlatform.OSXPlayer: return "macos";
                case RuntimePlatform.LinuxPlayer: return "linux";
                case RuntimePlatform.WindowsEditor:
                case RuntimePlatform.OSXEditor:
                case RuntimePlatform.LinuxEditor: return "editor";
                default: return "other";
            }
        }

        public static string Locale()
        {
            var name = System.Globalization.CultureInfo.CurrentCulture.Name;
            return string.IsNullOrEmpty(name) ? Application.systemLanguage.ToString() : name;
        }

        public static string Clip(string s, int max) => s == null ? "" : s.Length <= max ? s : s.Substring(0, max);
    }
}
