using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace ViKPI.Internal
{
    internal enum RequestKind
    {
        Start,
        Batch,
        Frames,
        End,
    }

    internal sealed class OutboxItem
    {
        public long Id;
        public RequestKind Kind;
        public string SessionId;
        public int Seq;
        public bool Gzipped;
        public string FilePath;
        public long Bytes;
        public int Attempts;
        public float NextAttemptAt;

        public bool IsFrames => Kind == RequestKind.Frames;

        public string Path
        {
            get
            {
                switch (Kind)
                {
                    case RequestKind.Start: return "/v1/sessions";
                    case RequestKind.Batch: return "/v1/sessions/" + SessionId + "/batch";
                    case RequestKind.Frames: return "/v1/sessions/" + SessionId + "/frames/" + Seq.ToString(CultureInfo.InvariantCulture);
                    default: return "/v1/sessions/" + SessionId + "/end";
                }
            }
        }
    }

    /// <summary>
    /// Durable, ordered request queue. Every request is written to disk before it is sent, so data
    /// survives offline play, app kills and crashes, and is delivered on a later launch.
    ///
    /// Two lanes run independently: JSON (start, batch, end; strictly in order, so the server always
    /// sees a session's start first) and frames (video chunks; can wait for Wi-Fi without holding up
    /// analytics). A frame chunk is never sent before its own session's start was accepted.
    /// </summary>
    internal sealed class Outbox
    {
        private const string Extension = ".vkq";
        private static readonly float[] Backoff = { 2, 5, 15, 30, 60, 120, 300 };

        private readonly object _lock = new object();
        private readonly string _dir;
        private readonly long _maxBytes;
        private readonly List<OutboxItem> _items = new List<OutboxItem>();
        private readonly bool _gzip;
        private long _nextId;
        private long _totalBytes;

        private readonly Lane _json;
        private readonly Lane _frames;

        public string Endpoint;
        public string ApiKey;
        public bool WifiOnlyFrames;

        /// <summary>Called on the main thread with the server's response to a session start sent this run.</summary>
        public Action<string, string> OnSessionStarted;

        /// <summary>Called when the server rejects the key; the SDK stops sending for this run.</summary>
        public Action OnUnauthorized;

        private bool _halted;

        public Outbox(string directory, long maxBytes)
        {
            _dir = directory;
            _maxBytes = maxBytes;
#if UNITY_WEBGL && !UNITY_EDITOR
            _gzip = false; // No System.IO.Compression in the browser runtime.
#else
            _gzip = true;
#endif
            _json = new Lane(this, frames: false);
            _frames = new Lane(this, frames: true);
            Directory.CreateDirectory(_dir);
            Restore();
        }

        public int PendingCount
        {
            get { lock (_lock) return _items.Count; }
        }

        /// <summary>Queues a JSON request. Thread-safe.</summary>
        public void EnqueueJson(RequestKind kind, string sessionId, string json)
        {
            var bytes = Encoding.UTF8.GetBytes(json);
            Enqueue(kind, sessionId, 0, _gzip && bytes.Length > 512 ? Gzip(bytes) : bytes, _gzip && bytes.Length > 512);
        }

        /// <summary>Queues a frame chunk. Thread-safe; called from the encoder thread.</summary>
        public void EnqueueFrames(string sessionId, int seq, byte[] chunk) => Enqueue(RequestKind.Frames, sessionId, seq, chunk, false);

        private void Enqueue(RequestKind kind, string sessionId, int seq, byte[] body, bool gzipped)
        {
            OutboxItem item;
            lock (_lock)
            {
                item = new OutboxItem { Id = ++_nextId, Kind = kind, SessionId = sessionId, Seq = seq, Gzipped = gzipped, Bytes = body.Length };
                item.FilePath = System.IO.Path.Combine(_dir, FileName(item));
            }
            try
            {
                File.WriteAllBytes(item.FilePath, body);
            }
            catch (Exception e)
            {
                // Disk full or storage unavailable: keep it in memory for this run.
                Log.Debug("Could not persist request: " + e.Message);
                item.FilePath = null;
                lock (_lock) _memoryBodies[item.Id] = body;
            }
            lock (_lock)
            {
                Insert(item);
                _totalBytes += item.Bytes;
                EnforceLimit();
            }
        }

        private readonly Dictionary<long, byte[]> _memoryBodies = new Dictionary<long, byte[]>();

        /// <summary>Starts or continues uploads. Call every frame from the main thread.</summary>
        public void Pump()
        {
            if (_halted || string.IsNullOrEmpty(Endpoint) || string.IsNullOrEmpty(ApiKey)) return;
            if (Application.internetReachability == NetworkReachability.NotReachable) return;
            _json.Pump();
            _frames.Pump();
        }

        public bool IsIdle => _json.Idle && _frames.Idle;

        private OutboxItem NextFor(bool frames)
        {
            lock (_lock)
            {
                for (var i = 0; i < _items.Count; i++)
                {
                    var it = _items[i];
                    if (it.IsFrames != frames) continue;
                    if (!frames) return it; // JSON lane is strictly ordered: head of line only.
                    if (WifiOnlyFrames && Application.internetReachability != NetworkReachability.ReachableViaLocalAreaNetwork) return null;
                    if (HasPendingStart(it.SessionId)) continue;
                    return it;
                }
                return null;
            }
        }

        private bool HasPendingStart(string sessionId)
        {
            for (var i = 0; i < _items.Count; i++)
            {
                if (_items[i].Kind == RequestKind.Start && _items[i].SessionId == sessionId) return true;
            }
            return false;
        }

        private void Complete(OutboxItem item)
        {
            lock (_lock)
            {
                if (_items.Remove(item)) _totalBytes -= item.Bytes;
                _memoryBodies.Remove(item.Id);
            }
            TryDelete(item.FilePath);
        }

        /// <summary>The server refused this session's video for good: drop its other chunks too.</summary>
        private void DropFramesOf(string sessionId)
        {
            List<OutboxItem> drop;
            lock (_lock)
            {
                drop = _items.FindAll(i => i.IsFrames && i.SessionId == sessionId);
            }
            foreach (var d in drop) Complete(d);
        }

        private byte[] ReadBody(OutboxItem item)
        {
            lock (_lock)
            {
                if (_memoryBodies.TryGetValue(item.Id, out var b)) return b;
            }
            try { return item.FilePath != null ? File.ReadAllBytes(item.FilePath) : null; }
            catch (Exception) { return null; }
        }

        private void Insert(OutboxItem item)
        {
            // Ids are monotonic, but items from the encoder thread may arrive slightly later.
            var i = _items.Count;
            while (i > 0 && _items[i - 1].Id > item.Id) i--;
            _items.Insert(i, item);
        }

        private void EnforceLimit()
        {
            // Video goes first, oldest first; then analytics batches. Starts and ends are tiny and
            // keep session counts right, so they are never dropped.
            for (var pass = 0; pass < 2 && _totalBytes > _maxBytes; pass++)
            {
                for (var i = 0; i < _items.Count && _totalBytes > _maxBytes;)
                {
                    var it = _items[i];
                    var victim = pass == 0 ? it.IsFrames : it.Kind == RequestKind.Batch;
                    if (victim && !_json.IsSending(it) && !_frames.IsSending(it))
                    {
                        _items.RemoveAt(i);
                        _totalBytes -= it.Bytes;
                        _memoryBodies.Remove(it.Id);
                        TryDelete(it.FilePath);
                    }
                    else i++;
                }
            }
        }

        private void Restore()
        {
            string[] files;
            try { files = Directory.GetFiles(_dir, "*" + Extension); }
            catch (Exception) { return; }

            foreach (var f in files)
            {
                var item = Parse(f);
                if (item == null) { TryDelete(f); continue; }
                Insert(item);
                _totalBytes += item.Bytes;
                if (item.Id > _nextId) _nextId = item.Id;
            }
            if (_items.Count > 0) Log.Debug($"Restored {_items.Count} unsent requests from disk.");
        }

        // File name: {id:D12}_{kind}_{session}_{seq}_{g|r}.vkq
        private static string FileName(OutboxItem i) =>
            i.Id.ToString("D12", CultureInfo.InvariantCulture) + "_" + (int)i.Kind + "_" + i.SessionId + "_" +
            i.Seq.ToString(CultureInfo.InvariantCulture) + "_" + (i.Gzipped ? "g" : "r") + Extension;

        private static OutboxItem Parse(string path)
        {
            var parts = System.IO.Path.GetFileNameWithoutExtension(path).Split('_');
            if (parts.Length != 5) return null;
            if (!long.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var id)) return null;
            if (!int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var kind) || kind < 0 || kind > 3) return null;
            if (!Guid.TryParse(parts[2], out _)) return null;
            if (!int.TryParse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture, out var seq)) return null;
            long size;
            try { size = new FileInfo(path).Length; }
            catch (Exception) { return null; }
            return new OutboxItem { Id = id, Kind = (RequestKind)kind, SessionId = parts[2], Seq = seq, Gzipped = parts[4] == "g", FilePath = path, Bytes = size };
        }

        private static void TryDelete(string path)
        {
            if (path == null) return;
            try { File.Delete(path); }
            catch (Exception) { /* best effort */ }
        }

        private static byte[] Gzip(byte[] data)
        {
            using (var ms = new MemoryStream(data.Length / 3 + 64))
            {
                using (var gz = new GZipStream(ms, System.IO.Compression.CompressionLevel.Fastest, true))
                {
                    gz.Write(data, 0, data.Length);
                }
                return ms.ToArray();
            }
        }

        /// <summary>One request in flight at a time, with exponential backoff on failure.</summary>
        private sealed class Lane
        {
            private readonly Outbox _box;
            private readonly bool _frames;
            private UnityWebRequest _req;
            private OutboxItem _item;

            public Lane(Outbox box, bool frames)
            {
                _box = box;
                _frames = frames;
            }

            public bool Idle => _req == null && _box.NextFor(_frames) == null;

            public bool IsSending(OutboxItem item) => ReferenceEquals(_item, item);

            public void Pump()
            {
                if (_req != null)
                {
                    if (!_req.isDone) return;
                    Finish();
                }

                var next = _box.NextFor(_frames);
                if (next == null || next.NextAttemptAt > Time.realtimeSinceStartup) return;

                var body = _box.ReadBody(next);
                if (body == null)
                {
                    _box.Complete(next); // Lost from disk; nothing to send.
                    return;
                }

                var req = new UnityWebRequest(_box.Endpoint.TrimEnd('/') + next.Path, next.IsFrames ? "PUT" : "POST")
                {
                    uploadHandler = new UploadHandlerRaw(body) { contentType = next.IsFrames ? "application/octet-stream" : "application/json" },
                    downloadHandler = new DownloadHandlerBuffer(),
                    timeout = next.IsFrames ? 90 : 30,
                };
                req.SetRequestHeader("x-vikpi-key", _box.ApiKey);
                req.SetRequestHeader("Content-Type", next.IsFrames ? "application/octet-stream" : "application/json");
                if (next.Gzipped) req.SetRequestHeader("Content-Encoding", "gzip");
                _item = next;
                _req = req;
                req.SendWebRequest();
            }

            private void Finish()
            {
                var req = _req;
                var item = _item;
                _req = null;
                _item = null;
                var code = req.responseCode;
                var text = code >= 200 && code < 300 && item.Kind == RequestKind.Start ? req.downloadHandler.text : null;
                var error = req.error;
                var forbiddenBody = code == 403 ? req.downloadHandler?.text : null;
                req.Dispose();

                if (code >= 200 && code < 300)
                {
                    _box.Complete(item);
                    if (text != null) _box.OnSessionStarted?.Invoke(item.SessionId, text);
                    return;
                }

                if (code == 403 && forbiddenBody != null && forbiddenBody.Contains("APP_ID_MISMATCH"))
                {
                    Log.Error($"This app ({DeviceInfo.AppId()}) is not registered for this project. In the dashboard, open Project settings → Platforms and add it. Sending is paused until the next launch.");
                    _box._halted = true;
                    _box.OnUnauthorized?.Invoke();
                    return;
                }
                if (code == 401 || code == 403)
                {
                    Log.Error("The server rejected the API key. Check it under Project Settings → ViKPI. Sending is paused until the next launch.");
                    _box._halted = true;
                    _box.OnUnauthorized?.Invoke();
                    return;
                }

                var retryable = code == 0 || code == 408 || code == 425 || code == 429 || code >= 500;
                if (!retryable)
                {
                    // 4xx: the request itself is wrong, or the session is unknown/finished. Retrying can't help.
                    Log.Debug($"{item.Kind} {item.Path} rejected with {code}; dropping it.");
                    _box.Complete(item);
                    if (item.IsFrames && code == 409) _box.DropFramesOf(item.SessionId);
                    return;
                }

                var delay = Backoff[Math.Min(item.Attempts, Backoff.Length - 1)];
                item.Attempts++;
                item.NextAttemptAt = Time.realtimeSinceStartup + delay * UnityEngine.Random.Range(0.8f, 1.2f);
                Log.Debug($"{item.Kind} failed ({(code == 0 ? error : code.ToString(CultureInfo.InvariantCulture))}); retrying in {delay:0}s.");
            }
        }
    }
}
