using System.IO;
using UnityEditor;
using UnityEngine;
using ViKPI.Internal;

namespace ViKPI.Editor
{
    /// <summary>
    /// Stopping Play Mode is an "app quit" for the SDK: the session end and the last video chunk
    /// are saved to disk and, in a real game, sent on the next launch. In the Editor that would
    /// mean the replay only appears after the next Play. The Editor keeps running, so it uploads
    /// what is left right away instead.
    /// </summary>
    [InitializeOnLoad]
    internal static class VikpiEditorFlush
    {
        private const double StartDelaySec = 1.0; // let the encoder thread write the final chunk and end
        private const double GiveUpAfterSec = 60.0;

        private static Outbox _box;
        private static double _startAt;
        private static double _stopAt;

        static VikpiEditorFlush()
        {
            EditorApplication.playModeStateChanged += state =>
            {
                if (state == PlayModeStateChange.EnteredEditMode) Schedule();
                else if (state == PlayModeStateChange.ExitingEditMode) Stop();
            };
        }

        private static void Schedule()
        {
            var settings = VikpiSettings.Load();
            if (settings == null || !settings.RunInEditor || string.IsNullOrWhiteSpace(settings.ApiKey)) return;
            _startAt = EditorApplication.timeSinceStartup + StartDelaySec;
            _stopAt = _startAt + GiveUpAfterSec;
            EditorApplication.update -= Tick;
            EditorApplication.update += Tick;
        }

        private static void Tick()
        {
            var now = EditorApplication.timeSinceStartup;
            if (now < _startAt) return;
            if (EditorApplication.isPlayingOrWillChangePlaymode || now > _stopAt)
            {
                Stop();
                return;
            }
            if (_box == null)
            {
                var settings = VikpiSettings.Load();
                var dir = Path.Combine(Application.persistentDataPath, "vikpi", "outbox");
                if (settings == null || !Directory.Exists(dir) || Directory.GetFiles(dir, "*.vkq").Length == 0)
                {
                    Stop();
                    return;
                }
                var url = string.IsNullOrWhiteSpace(settings.Endpoint) ? VikpiSettings.DefaultEndpoint : settings.Endpoint.Trim();
                _box = new Outbox(dir, (long)settings.MaxOfflineStorageMb * 1024 * 1024)
                {
                    Endpoint = url,
                    ApiKey = settings.ApiKey.Trim(),
                };
                if (settings.DebugLogging) Debug.Log($"[ViKPI] Uploading {_box.PendingCount} request(s) left by the Play session.");
            }
            _box.Pump();
            if (_box.IsIdle) Stop();
        }

        private static void Stop()
        {
            EditorApplication.update -= Tick;
            _box = null;
        }
    }
}
