using System;
using System.IO;

namespace ViKPI.Internal
{
    /// <summary>
    /// Builds VKF1 frame chunks: the binary container the server stitches into a video.
    ///
    /// Layout, little-endian:
    ///   "VKF1" | width u16 | height u16 | count u32 | count × (tMs u32 | length u32 | JPEG bytes)
    ///
    /// All frames in a chunk share one size, and timestamps never decrease. See docs/protocol.md.
    /// Not thread-safe: owned by the encoder thread.
    /// </summary>
    internal sealed class FrameChunkWriter
    {
        public static readonly byte[] Magic = { (byte)'V', (byte)'K', (byte)'F', (byte)'1' };
        private const int HeaderSize = 12;

        private readonly int _maxBytes;
        private readonly int _maxFrames;
        private readonly long _maxSpanMs;
        private MemoryStream _body;
        private BinaryWriter _writer;
        private int _count;
        private long _lastT = -1;
        private long _firstT;

        public int Width { get; private set; }
        public int Height { get; private set; }
        public int Count => _count;

        public FrameChunkWriter(int maxBytes = 1_000_000, int maxFrames = 150, long maxSpanMs = 6000)
        {
            _maxBytes = maxBytes;
            _maxFrames = maxFrames;
            _maxSpanMs = maxSpanMs;
        }

        /// <summary>True if the frame can't join the current chunk; flush first.</summary>
        public bool NeedsFlushBefore(int width, int height, long tMs)
        {
            if (_count == 0) return false;
            return width != Width || height != Height || tMs < _lastT;
        }

        /// <summary>True once the chunk is big or long enough to send.</summary>
        public bool IsFull => _count > 0 && (_body.Length >= _maxBytes || _count >= _maxFrames || _lastT - _firstT >= _maxSpanMs);

        public void Add(long tMs, int width, int height, byte[] jpeg)
        {
            if (tMs < 0 || tMs > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(tMs));
            if (_count == 0)
            {
                Width = width;
                Height = height;
                _firstT = tMs;
                _body = new MemoryStream(Math.Max(64 * 1024, jpeg.Length * 8));
                _writer = new BinaryWriter(_body);
            }
            else if (width != Width || height != Height || tMs < _lastT)
            {
                throw new InvalidOperationException("Frame does not fit this chunk; flush first.");
            }
            _writer.Write((uint)tMs);
            _writer.Write((uint)jpeg.Length);
            _writer.Write(jpeg);
            _lastT = tMs;
            _count++;
        }

        /// <summary>Returns the finished chunk and resets, or null if empty.</summary>
        public byte[] Flush()
        {
            if (_count == 0) return null;
            _writer.Flush();
            var result = new byte[HeaderSize + _body.Length];
            Buffer.BlockCopy(Magic, 0, result, 0, 4);
            WriteU16(result, 4, Width);
            WriteU16(result, 6, Height);
            WriteU32(result, 8, (uint)_count);
            Buffer.BlockCopy(_body.GetBuffer(), 0, result, HeaderSize, (int)_body.Length);
            _writer.Dispose();
            _writer = null;
            _body = null;
            _count = 0;
            _lastT = -1;
            return result;
        }

        private static void WriteU16(byte[] b, int at, int v)
        {
            b[at] = (byte)v;
            b[at + 1] = (byte)(v >> 8);
        }

        private static void WriteU32(byte[] b, int at, uint v)
        {
            b[at] = (byte)v;
            b[at + 1] = (byte)(v >> 8);
            b[at + 2] = (byte)(v >> 16);
            b[at + 3] = (byte)(v >> 24);
        }
    }
}
