using System;
using System.Collections.Generic;
using System.Threading;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;

namespace ViKPI.Internal
{
    internal struct RecordingConfig
    {
        public int Fps;
        public int MaxDimension;
        public int Quality;
        public long MaxDurationMs;
    }

    /// <summary>
    /// Captures the screen at a low frame rate and turns it into VKF1 chunks, without stalling the game:
    ///
    ///   end of frame → copy backbuffer to a RenderTexture → downscale on the GPU →
    ///   AsyncGPUReadback → (encoder thread) paint privacy masks → JPEG → append to chunk → outbox
    ///
    /// The only main-thread work is two GPU blits and a memcpy of a ~1–2 MB buffer per captured frame.
    /// Where async readback is unavailable (WebGL, some GLES2 devices) it falls back to a synchronous
    /// ReadPixels at a reduced rate.
    /// </summary>
    internal sealed class FrameRecorder : IDisposable
    {
        /// <summary>Frames in flight between capture and encoded. Beyond this, captures are skipped.</summary>
        private const int MaxInFlight = 3;

        private readonly RecordingConfig _config;
        private readonly string _sessionId;
        private readonly Outbox _outbox;
        private readonly SerialWorker _encoder;
        private readonly FrameChunkWriter _chunk = new FrameChunkWriter();
        private readonly bool _asyncReadback;
        private readonly bool _flipY;
        private readonly List<Rect> _maskScratch = new List<Rect>();

        private RenderTexture _full;
        private RenderTexture _small;
        private Texture2D _cpu;
        private int _inFlight;
        private int _chunksQueued;
        private double _nextCaptureAt;
        private bool _stopped;

        public bool Paused;

        public FrameRecorder(RecordingConfig config, string sessionId, Outbox outbox)
        {
            _config = config;
            _sessionId = sessionId;
            _outbox = outbox;
            _encoder = new SerialWorker("ViKPI.Encoder");
            _asyncReadback = SystemInfo.supportsAsyncGPUReadback;
            // CaptureScreenshotIntoRenderTexture returns an image that is upside down on APIs whose
            // texture origin is the top-left (D3D, Metal, Vulkan).
            _flipY = SystemInfo.graphicsUVStartsAtTop;
            if (!_asyncReadback && _config.Fps > 4) _config.Fps = 4;
        }

        /// <summary>Chunks handed to the outbox so far: the frameChunks count the session end reports.</summary>
        public int ChunksQueued => Volatile.Read(ref _chunksQueued);

        public bool Stopped => _stopped;

        /// <summary>Call from a WaitForEndOfFrame coroutine so the backbuffer holds the finished frame.</summary>
        public void OnEndOfFrame(long sessionMs)
        {
            if (_stopped || Paused) return;
            if (sessionMs > _config.MaxDurationMs)
            {
                Log.Debug("Recording reached its maximum duration.");
                Stop();
                return;
            }

            var now = Time.realtimeSinceStartupAsDouble;
            if (now < _nextCaptureAt) return;
            // Keep cadence stable without bursting after a hitch.
            _nextCaptureAt = Math.Max(_nextCaptureAt + 1.0 / _config.Fps, now);

            if (Volatile.Read(ref _inFlight) >= MaxInFlight) return; // Encoder is behind: skip this frame.

            var sw = Screen.width;
            var sh = Screen.height;
            if (sw < 16 || sh < 16) return;
            var scale = Mathf.Min(1f, (float)_config.MaxDimension / Mathf.Max(sw, sh));
            var w = Mathf.Max(16, Mathf.RoundToInt(sw * scale) & ~1);
            var h = Mathf.Max(16, Mathf.RoundToInt(sh * scale) & ~1);

            EnsureTargets(sw, sh, w, h);
            ScreenCapture.CaptureScreenshotIntoRenderTexture(_full);
            if (_flipY) Graphics.Blit(_full, _small, new Vector2(1, -1), new Vector2(0, 1));
            else Graphics.Blit(_full, _small);

            var masks = SnapshotMasks(sw, sh, w, h);
            Interlocked.Increment(ref _inFlight);

            if (_asyncReadback)
            {
                AsyncGPUReadback.Request(_small, 0, TextureFormat.RGBA32, req => OnReadback(req, sessionMs, w, h, masks));
            }
            else
            {
                var prev = RenderTexture.active;
                RenderTexture.active = _small;
                _cpu.ReadPixels(new Rect(0, 0, w, h), 0, 0, false);
                RenderTexture.active = prev;
                var data = _cpu.GetRawTextureData<byte>();
                var copy = new NativeArray<byte>(data.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
                copy.CopyFrom(data);
                _encoder.Post(() => Encode(copy, sessionMs, w, h, masks));
            }
        }

        private void OnReadback(AsyncGPUReadbackRequest req, long t, int w, int h, RectInt[] masks)
        {
            if (req.hasError || _stopped)
            {
                Interlocked.Decrement(ref _inFlight);
                return;
            }
            var data = req.GetData<byte>();
            // The readback buffer is only valid inside this callback.
            var copy = new NativeArray<byte>(data.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
            copy.CopyFrom(data);
            _encoder.Post(() => Encode(copy, t, w, h, masks));
        }

        /// <summary>Encoder thread.</summary>
        private void Encode(NativeArray<byte> rgba, long t, int w, int h, RectInt[] masks)
        {
            try
            {
                if (masks != null) PaintMasks(rgba, w, h, masks);
                byte[] jpeg;
                using (var encoded = ImageConversion.EncodeNativeArrayToJPG(rgba, GraphicsFormat.R8G8B8A8_UNorm, (uint)w, (uint)h, 0, _config.Quality))
                {
                    jpeg = encoded.ToArray();
                }
                if (_chunk.NeedsFlushBefore(w, h, t)) EmitChunk();
                _chunk.Add(t, w, h, jpeg);
                if (_chunk.IsFull) EmitChunk();
            }
            finally
            {
                rgba.Dispose();
                Interlocked.Decrement(ref _inFlight);
            }
        }

        /// <summary>Encoder thread.</summary>
        private void EmitChunk()
        {
            var bytes = _chunk.Flush();
            if (bytes == null) return;
            var seq = Interlocked.Increment(ref _chunksQueued) - 1;
            _outbox.EnqueueFrames(_sessionId, seq, bytes);
        }

        /// <summary>
        /// Sends the partial chunk, then runs <paramref name="then"/> on the encoder thread with the
        /// final chunk count. Used on pause and at session end.
        /// </summary>
        public void FlushChunk(Action<int> then = null)
        {
            _encoder.Post(() =>
            {
                EmitChunk();
                then?.Invoke(ChunksQueued);
            });
        }

        /// <summary>Blocks briefly for in-flight frames, for app quit where nothing runs afterwards.</summary>
        public void WaitForEncoder(int timeoutMs) => _encoder.WaitIdle(timeoutMs);

        public void Stop()
        {
            if (_stopped) return;
            _stopped = true;
            FlushChunk();
        }

        private RectInt[] SnapshotMasks(int sw, int sh, int w, int h)
        {
            VikpiMask.CollectScreenRects(_maskScratch);
            if (_maskScratch.Count == 0) return null;
            var sx = (float)w / sw;
            var sy = (float)h / sh;
            var result = new RectInt[_maskScratch.Count];
            for (var i = 0; i < _maskScratch.Count; i++)
            {
                var r = _maskScratch[i];
                // Screen space and texture rows share a bottom-left origin. Round outwards.
                var x0 = Mathf.Clamp(Mathf.FloorToInt(r.xMin * sx), 0, w);
                var y0 = Mathf.Clamp(Mathf.FloorToInt(r.yMin * sy), 0, h);
                var x1 = Mathf.Clamp(Mathf.CeilToInt(r.xMax * sx), 0, w);
                var y1 = Mathf.Clamp(Mathf.CeilToInt(r.yMax * sy), 0, h);
                result[i] = new RectInt(x0, y0, x1 - x0, y1 - y0);
            }
            return result;
        }

        private static void PaintMasks(NativeArray<byte> rgba, int w, int h, RectInt[] masks)
        {
            foreach (var m in masks)
            {
                for (var y = m.yMin; y < m.yMax; y++)
                {
                    var row = y * w * 4;
                    for (var x = m.xMin; x < m.xMax; x++)
                    {
                        var i = row + x * 4;
                        rgba[i] = 24;
                        rgba[i + 1] = 24;
                        rgba[i + 2] = 27;
                        rgba[i + 3] = 255;
                    }
                }
            }
        }

        private void EnsureTargets(int sw, int sh, int w, int h)
        {
            if (_full == null || _full.width != sw || _full.height != sh)
            {
                Release(ref _full);
                _full = new RenderTexture(sw, sh, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "ViKPI Capture" };
                _full.Create();
            }
            if (_small == null || _small.width != w || _small.height != h)
            {
                Release(ref _small);
                _small = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB)
                {
                    name = "ViKPI Frame",
                    filterMode = FilterMode.Bilinear,
                };
                _small.Create();
                if (!_asyncReadback)
                {
                    if (_cpu != null) UnityEngine.Object.Destroy(_cpu);
                    _cpu = new Texture2D(w, h, TextureFormat.RGBA32, false, false) { name = "ViKPI Readback" };
                }
            }
        }

        private static void Release(ref RenderTexture rt)
        {
            if (rt == null) return;
            rt.Release();
            UnityEngine.Object.Destroy(rt);
            rt = null;
        }

        public void Dispose()
        {
            _stopped = true;
            _encoder.Dispose();
            Release(ref _full);
            Release(ref _small);
            if (_cpu != null) UnityEngine.Object.Destroy(_cpu);
            _cpu = null;
        }
    }
}
