using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace ViKPI.Internal
{
    /// <summary>
    /// The SDK's single long-lived object. Owns the session lifecycle and wires the trackers,
    /// recorder and outbox together. Created by <see cref="Boot"/>; survives scene loads.
    /// </summary>
    [AddComponentMenu("")]
    [DefaultExecutionOrder(-10000)]
    internal sealed class VikpiRuntime : MonoBehaviour
    {
        private const string UserIdKey = "vikpi.user_id";
        private const float FirstFlushDelaySec = 2f;

        internal static VikpiRuntime Instance { get; private set; }

        private VikpiSettings _settings;
        private Outbox _outbox;
        private readonly EventBuffer _buffer = new EventBuffer();
        private readonly TouchTracker _touch = new TouchTracker();
        private readonly PerfSampler _perf = new PerfSampler();
        private ErrorCapture _errors;
        private FrameRecorder _recorder;
        private string _dataDir;

        private SessionClock _clock;
        private string _sessionId;
        private bool _ended = true;
        private volatile string _scene = "";
        private string _userId;
        private float _flushIntervalSec = 10f;
        private float _nextFlushAt;
        private bool _recordingPaused;
        private DateTime? _backgroundedAt;
        private long _backgroundedAtMs;
        /// <summary>Read by the encoder thread so a late marker write can't outlive a quick return.</summary>
        private volatile bool _inBackground;
        private bool _quitting;

        internal bool HasSession => !_ended && _sessionId != null;
        internal string SessionId => HasSession ? _sessionId : null;
        internal bool IsRecording => HasSession && _recorder != null && !_recorder.Stopped && !_recorder.Paused;

        // ---------- startup ----------

        /// <summary>A start that is waiting for the player's consent.</summary>
        private sealed class PendingStart
        {
            public VikpiSettings Settings;
            public string ApiKey;
            public string Endpoint;
        }

        private static PendingStart _pending;

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
        private static void ResetStatics() // Supports Enter Play Mode without domain reload.
        {
            Instance = null;
            _pending = null;
        }

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        private static void AutoBoot()
        {
            var settings = VikpiSettings.Load();
            if (settings != null && settings.AutoStart) Boot(settings, null, null, explicitInit: false);
        }

        internal static void Boot(VikpiSettings settings, string apiKey, string endpoint, bool explicitInit)
        {
            if (Instance != null)
            {
                if (explicitInit) Log.Debug("Init() called while already running; ignored.");
                return;
            }
            if (settings == null) settings = VikpiSettings.CreateDefault();
            Log.Verbose = settings.DebugLogging;
            VikpiMask.MaskTextInputs = settings.MaskTextInputs;

            if (settings.AppTargetsChildren)
            {
                Log.Info("\"App Targets Children\" is on: ViKPI collects nothing in this build.");
                return;
            }

            if (Application.isEditor && !settings.RunInEditor)
            {
                if (explicitInit || settings.DebugLogging)
                    Log.Info("Not sending data from the Editor. Turn on \"Run In Editor\" under Project Settings → ViKPI to test.");
                return;
            }

            // Nothing is collected, and no id is created, before the player agrees.
            if (!ConsentStore.Allows(settings))
            {
                _pending = new PendingStart { Settings = settings, ApiKey = apiKey, Endpoint = endpoint };
                if (settings.ConsentMode == VikpiConsentMode.BuiltInPrompt && ConsentStore.Read() == VikpiConsentStatus.Unknown)
                    ConsentPrompt.Show(settings, SetConsent);
                else
                    Log.Debug("Waiting for the player's consent (Vikpi.SetConsent) before starting.");
                return;
            }
            _pending = null;

            var key = string.IsNullOrWhiteSpace(apiKey) ? settings.ApiKey : apiKey;
            key = key?.Trim() ?? "";
            if (!key.StartsWith("vk_pub_", StringComparison.Ordinal))
            {
                Log.Warn("No valid API key. Paste your project key (vk_pub_…) under Project Settings → ViKPI.");
                return;
            }
            var url = string.IsNullOrWhiteSpace(endpoint) ? settings.Endpoint : endpoint;
            if (string.IsNullOrWhiteSpace(url)) url = VikpiSettings.DefaultEndpoint;

            var go = new GameObject("ViKPI");
            DontDestroyOnLoad(go);
            var runtime = go.AddComponent<VikpiRuntime>();
            runtime.Setup(settings, key, url.Trim());
        }

        private void Setup(VikpiSettings settings, string key, string endpoint)
        {
            Instance = this;
            _settings = settings;
            _dataDir = Path.Combine(Application.persistentDataPath, "vikpi");
            _outbox = new Outbox(Path.Combine(_dataDir, "outbox"), (long)settings.MaxOfflineStorageMb * 1024 * 1024)
            {
                Endpoint = endpoint,
                ApiKey = key,
                OnSessionStarted = HandleStartResponse,
            };
            if (settings.CaptureErrors) _errors = new ErrorCapture(() => _clock?.NowMs ?? 0, () => _scene, () => _ended ? null : _buffer);

            _userId = PlayerPrefs.GetString(UserIdKey, "");
            if (_userId.Length == 0) _userId = null;

            SceneManager.activeSceneChanged += OnActiveSceneChanged;
            SceneManager.sceneLoaded += OnSceneLoaded;
            _scene = SceneManager.GetActiveScene().name ?? "";

            CloseSessionLeftOpen();
            StartSession();
            StartCoroutine(EndOfFrameLoop());
            Log.Debug($"Started. Endpoint {endpoint}, session {_sessionId}.");
        }

        // ---------- session lifecycle ----------

        private void StartSession()
        {
            _sessionId = Guid.NewGuid().ToString();
            _clock = new SessionClock();
            _ended = false;
            _errors?.ResetSession();
            _perf.Reset();
            _flushIntervalSec = 10f;
            _nextFlushAt = Time.realtimeSinceStartup + FirstFlushDelaySec;

            var w = new JsonWriter(512).BeginObject()
                .Prop("sessionId", _sessionId)
                .Prop("deviceId", DeviceInfo.DeviceId());
            if (_userId != null) w.Prop("userId", _userId);
            w.Prop("startedAt", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
                .Prop("sdkVersion", Vikpi.SdkVersion)
                .Prop("appVersion", DeviceInfo.Clip(Application.version, 64))
                .Prop("platform", DeviceInfo.Platform())
                .Prop("appId", DeviceInfo.Clip(DeviceInfo.AppId(), 256))
                .Prop("os", DeviceInfo.Clip(SystemInfo.operatingSystem, 128))
                .Prop("deviceModel", DeviceInfo.Clip(SystemInfo.deviceModel, 128))
                .Prop("screenWidth", Math.Max(1, Screen.width))
                .Prop("screenHeight", Math.Max(1, Screen.height))
                .Prop("memoryMb", Math.Max(0, SystemInfo.systemMemorySize))
                .Prop("locale", DeviceInfo.Clip(DeviceInfo.Locale(), 32));
            var dpi = Screen.dpi;
            if (dpi > 0 && dpi < 2000) w.Prop("dpi", Math.Round(dpi, 1));
            _outbox.EnqueueJson(RequestKind.Start, _sessionId, w.EndObject().ToString());

            if (_scene.Length > 0) TrackSystem("$scene", new Dictionary<string, object> { { "name", _scene } });
        }

        /// <summary>Server accepted a session start: apply remote config and maybe begin recording.</summary>
        private void HandleStartResponse(string sessionId, string json)
        {
            if (sessionId != _sessionId || _ended) return; // A start from an earlier launch, sent late.
            StartResponseDto res;
            try { res = JsonUtility.FromJson<StartResponseDto>(json); }
            catch (Exception) { return; }
            if (res == null) return;

            if (res.flushIntervalSec >= 2 && res.flushIntervalSec <= 300) _flushIntervalSec = res.flushIntervalSec;
            var rec = res.recording;
            if (rec == null || !rec.enabled || !_settings.AllowRecording || _recorder != null) return;

            _outbox.WifiOnlyFrames = rec.wifiOnly;
            _recorder = new FrameRecorder(new RecordingConfig
            {
                Fps = Mathf.Clamp(rec.fps, 1, 30),
                MaxDimension = Mathf.Clamp(rec.maxDimension, 240, 1280),
                Quality = Mathf.Clamp(rec.quality, 10, 95),
                MaxDurationMs = Math.Max(30, rec.maxDurationSec) * 1000L,
            }, _sessionId, _outbox)
            { Paused = _recordingPaused };
            Log.Debug($"Recording at {rec.fps} fps, {rec.maxDimension}px.");
        }

        private void EndSession(long durationMs)
        {
            if (_ended) return;
            FlushNow();
            _ended = true;
            var sid = _sessionId;
            var rec = _recorder;
            _recorder = null;
            DeleteOpenSessionMarker();

            if (rec == null)
            {
                _outbox.EnqueueJson(RequestKind.End, sid, EndJson(durationMs, 0));
                return;
            }
            rec.Stop();
            // The end must report the final chunk count, known only after the encoder drains.
            rec.FlushChunk(chunks => _outbox.EnqueueJson(RequestKind.End, sid, EndJson(durationMs, chunks)));
            if (_quitting) rec.WaitForEncoder(800);
            rec.Dispose();
        }

        private static string EndJson(long durationMs, int chunks) =>
            new JsonWriter(64).BeginObject().Prop("durationMs", Math.Max(0, durationMs)).Prop("frameChunks", chunks).EndObject().ToString();

        // ---------- the app going to the background and back ----------

        /// <summary>
        /// Scripts recompiled during Play Mode ("Recompile and continue playing"): Unity rebuilt this
        /// component but our non-serializable state (outbox, clock, recorder) is gone. Replace it with
        /// a fresh instance instead of throwing every frame and on quit.
        /// </summary>
        private bool LostStateAfterReload => _outbox == null;

        private void RecoverAfterReload()
        {
            enabled = false;
            Destroy(gameObject);
            if (Instance != null && Instance != this) return;
            Instance = null;
            var settings = VikpiSettings.Load();
            Log.Debug("Scripts were reloaded during Play Mode; restarting the SDK with a new session.");
            if (settings != null && settings.AutoStart) Boot(settings, null, null, explicitInit: false);
        }

        private void OnApplicationPause(bool paused)
        {
            if (LostStateAfterReload) return;
            if (paused) GoBackground();
            else ReturnForeground();
        }

        private void GoBackground()
        {
            if (_ended || _backgroundedAt.HasValue) return;
            _backgroundedAt = DateTime.UtcNow;
            _inBackground = true;
            _backgroundedAtMs = _clock.NowMs;
            TrackSystem("$pause", null);
            FlushNow();

            // Mobile OSes may kill a backgrounded app without warning. Leave a note so the next
            // launch can close this session with the right duration and chunk count.
            var sid = _sessionId;
            var durationMs = _backgroundedAtMs;
            if (_recorder != null) _recorder.FlushChunk(chunks => WriteOpenSessionMarker(sid, durationMs, chunks));
            else WriteOpenSessionMarker(sid, durationMs, 0);
            PlayerPrefs.Save();
        }

        private void ReturnForeground()
        {
            if (!_backgroundedAt.HasValue) return;
            var away = DateTime.UtcNow - _backgroundedAt.Value;
            _backgroundedAt = null;
            _inBackground = false;
            _perf.Reset();
            if (_ended) return;

            if (away.TotalSeconds > _settings.SessionTimeoutSeconds)
            {
                EndSession(_backgroundedAtMs);
                StartSession();
            }
            else
            {
                DeleteOpenSessionMarker();
                TrackSystem("$resume", new Dictionary<string, object> { { "away_ms", (long)away.TotalMilliseconds } });
            }
        }

        private void OnApplicationQuit()
        {
            if (LostStateAfterReload) return;
            _quitting = true;
            if (!_ended) EndSession(_clock.NowMs);
            // Requests are already on disk; the next launch delivers anything unsent.
        }

        private string MarkerPath => Path.Combine(_dataDir, "open_session");

        private void WriteOpenSessionMarker(string sid, long durationMs, int chunks)
        {
            if (!_inBackground) return;
            try
            {
                File.WriteAllText(MarkerPath, sid + "|" + durationMs.ToString(CultureInfo.InvariantCulture) + "|" + chunks.ToString(CultureInfo.InvariantCulture));
            }
            catch (Exception) { /* best effort */ }
        }

        private void DeleteOpenSessionMarker()
        {
            try { File.Delete(MarkerPath); }
            catch (Exception) { /* best effort */ }
        }

        /// <summary>The previous launch was killed in the background: end that session now.</summary>
        private void CloseSessionLeftOpen()
        {
            string text;
            try
            {
                if (!File.Exists(MarkerPath)) return;
                text = File.ReadAllText(MarkerPath);
            }
            catch (Exception) { return; }
            DeleteOpenSessionMarker();

            var parts = text.Split('|');
            if (parts.Length != 3 || !Guid.TryParse(parts[0], out _)) return;
            if (!long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var duration)) return;
            if (!int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out var chunks)) return;
            _outbox.EnqueueJson(RequestKind.End, parts[0], EndJson(duration, chunks));
            Log.Debug("Closed a session left open by the previous launch.");
        }

        // ---------- per frame ----------

        private void Update()
        {
            if (LostStateAfterReload)
            {
                RecoverAfterReload();
                return;
            }
            if (!_ended && !_backgroundedAt.HasValue)
            {
                var t = _clock.NowMs;
                if (_settings.TrackTouches) _touch.Update(t, _scene, _buffer);
                if (_settings.TrackPerformance) _perf.Update(t, _scene, _buffer);
                if (Time.realtimeSinceStartup >= _nextFlushAt) FlushNow();
            }
            _outbox.Pump();
        }

        private IEnumerator EndOfFrameLoop()
        {
            var wait = new WaitForEndOfFrame();
            while (true)
            {
                yield return wait;
                if (_recorder != null && !_ended && !_backgroundedAt.HasValue) _recorder.OnEndOfFrame(_clock.NowMs);
            }
        }

        // ---------- public API backing ----------

        internal void TrackEvent(string name, IDictionary<string, object> props)
        {
            if (_ended) return;
            _buffer.Add(new EventItem { T = _clock.NowMs, Name = name, PropsJson = JsonWriter.Props(props) });
        }

        private void TrackSystem(string name, IDictionary<string, object> props) => TrackEvent(name, props);

        internal static void SetUserId(string userId)
        {
            if (string.IsNullOrWhiteSpace(userId)) userId = null;
            if (userId == null) PlayerPrefs.DeleteKey(UserIdKey);
            else PlayerPrefs.SetString(UserIdKey, userId);
            var rt = Instance;
            if (rt == null || rt._userId == userId) return;
            rt._userId = userId;
            if (userId != null) rt.TrackSystem("$identify", new Dictionary<string, object> { { "user_id", userId } });
        }

        internal void SetRecordingPaused(bool paused)
        {
            _recordingPaused = paused;
            if (_recorder != null) _recorder.Paused = paused;
        }

        internal void FlushNow()
        {
            _nextFlushAt = Time.realtimeSinceStartup + _flushIntervalSec;
            if (_sessionId == null) return;
            var batches = _buffer.Drain();
            if (batches == null) return;
            foreach (var body in batches) _outbox.EnqueueJson(RequestKind.Batch, _sessionId, body);
        }

        internal static void ShutdownInstance()
        {
            var rt = Instance;
            if (rt == null) return;
            if (!rt._ended) rt.EndSession(rt._clock.NowMs);
            Destroy(rt.gameObject);
        }

        // ---------- consent and data rights ----------

        /// <summary>Records the player's choice. Granting starts a pending start; refusing stops and erases unsent data.</summary>
        internal static void SetConsent(bool granted)
        {
            ConsentStore.Write(granted);
            if (granted)
            {
                if (Instance != null) return;
                var p = _pending;
                var settings = p?.Settings ?? VikpiSettings.Load();
                if (p != null) Boot(p.Settings, p.ApiKey, p.Endpoint, explicitInit: true);
                else if (settings != null && settings.AutoStart) Boot(settings, null, null, explicitInit: false);
                return;
            }
            StopAndEraseQueue();
            Log.Debug("Consent refused or withdrawn: stopped, unsent data erased.");
        }

        /// <summary>Stops without sending anything more and deletes data still waiting on the device.</summary>
        private static void StopAndEraseQueue()
        {
            var rt = Instance;
            if (rt != null)
            {
                rt._ended = true; // no session end is sent after a withdrawal
                rt._recorder?.Dispose();
                rt._recorder = null;
                // Deactivating stops Update and the capture coroutine at once; OnDestroy then
                // unhooks scene and log callbacks as usual.
                rt.gameObject.SetActive(false);
                Destroy(rt.gameObject);
            }
            try
            {
                var dir = Path.Combine(Application.persistentDataPath, "vikpi");
                if (Directory.Exists(dir)) Directory.Delete(dir, true);
            }
            catch (Exception) { /* best effort: files are retried and pruned on a later launch */ }
        }

        /// <summary>
        /// Asks the server to delete everything recorded from this install, then forgets the
        /// install id and user id locally. Also withdraws consent.
        /// </summary>
        internal static void RequestDeletion(Action<bool> onDone)
        {
            var settings = Instance != null ? Instance._settings : VikpiSettings.Load();
            var key = Instance != null ? Instance._outbox.ApiKey : settings?.ApiKey?.Trim();
            var url = Instance != null ? Instance._outbox.Endpoint : settings?.Endpoint?.Trim();
            if (string.IsNullOrWhiteSpace(url)) url = VikpiSettings.DefaultEndpoint;

            var deviceId = DeviceInfo.PeekDeviceId();
            SetConsent(false);
            PlayerPrefs.DeleteKey(UserIdKey);
            if (deviceId == null || string.IsNullOrEmpty(key))
            {
                DeviceInfo.ResetDeviceId();
                onDone?.Invoke(true); // nothing was ever sent from this install
                return;
            }

            var body = System.Text.Encoding.UTF8.GetBytes(new JsonWriter(64).BeginObject().Prop("deviceId", deviceId).EndObject().ToString());
            var req = new UnityEngine.Networking.UnityWebRequest(url.TrimEnd('/') + "/v1/privacy/delete", "POST")
            {
                uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(body),
                downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer(),
                timeout = 30,
            };
            req.SetRequestHeader("x-vikpi-key", key);
            req.SetRequestHeader("Content-Type", "application/json");
            req.SendWebRequest().completed += _ =>
            {
                var ok = req.result == UnityEngine.Networking.UnityWebRequest.Result.Success;
                if (ok) DeviceInfo.ResetDeviceId(); // keep it on failure so the request can be retried
                else Log.Warn("Data deletion request failed (" + req.error + "). Call Vikpi.RequestDataDeletion() again later.");
                req.Dispose();
                onDone?.Invoke(ok);
            };
        }

        // ---------- scenes ----------

        private void OnActiveSceneChanged(Scene from, Scene to) => NoteScene(to.name);

        private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            if (mode == LoadSceneMode.Single) NoteScene(scene.name);
        }

        private void NoteScene(string name)
        {
            name = name ?? "";
            if (name == _scene) return;
            _scene = name;
            if (!_ended && name.Length > 0) TrackSystem("$scene", new Dictionary<string, object> { { "name", name } });
        }

        private void OnDestroy()
        {
            if (Instance != this) return;
            SceneManager.activeSceneChanged -= OnActiveSceneChanged;
            SceneManager.sceneLoaded -= OnSceneLoaded;
            _errors?.Dispose();
            _recorder?.Dispose();
            _recorder = null;
            Instance = null;
        }

        [Serializable]
        private sealed class StartResponseDto
        {
            public RecordingDto recording;
            public float flushIntervalSec;
        }

        [Serializable]
        private sealed class RecordingDto
        {
            public bool enabled;
            public int fps;
            public int maxDimension;
            public int quality;
            public int maxDurationSec;
            public bool wifiOnly;
        }
    }
}
