// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;

namespace WPFMA.Vrca
{
    internal sealed class WPFMAVrcaLzma
    {
        private const int TopValue = 1 << 24;
        private const int BitModelTotalBits = 11;
        private const uint BitModelTotal = 1 << BitModelTotalBits;
        private const int MoveBits = 5;
        private const uint ProbInit = BitModelTotal >> 1;

        private const int NumPosBitsMax = 4;
        private const int NumPosStatesMax = 1 << NumPosBitsMax;
        private const int NumStates = 12;
        private const int NumLenToPosStates = 4;
        private const int NumAlignBits = 4;
        private const int StartPosModelIndex = 4;
        private const int EndPosModelIndex = 14;
        private const int NumFullDistances = 1 << (EndPosModelIndex / 2);
        private const int MatchMinLen = 2;

        private sealed class LenDecoder
        {
            public readonly ushort[] Choice = new ushort[2];
            public readonly ushort[] Low = new ushort[NumPosStatesMax << 3];
            public readonly ushort[] Mid = new ushort[NumPosStatesMax << 3];
            public readonly ushort[] High = new ushort[256];

            public void Reset()
            {
                Fill(Choice);
                Fill(Low);
                Fill(Mid);
                Fill(High);
            }
        }

        private readonly ushort[] isMatch = new ushort[NumStates << NumPosBitsMax];
        private readonly ushort[] isRep = new ushort[NumStates];
        private readonly ushort[] isRepG0 = new ushort[NumStates];
        private readonly ushort[] isRepG1 = new ushort[NumStates];
        private readonly ushort[] isRepG2 = new ushort[NumStates];
        private readonly ushort[] isRep0Long = new ushort[NumStates << NumPosBitsMax];
        private readonly ushort[] posSlot = new ushort[NumLenToPosStates << 6];
        private readonly ushort[] posDecoders = new ushort[NumFullDistances];
        private readonly ushort[] posAlign = new ushort[1 << NumAlignBits];
        private readonly LenDecoder lenDecoder = new LenDecoder();
        private readonly LenDecoder repLenDecoder = new LenDecoder();
        private ushort[] literalProbs;

        private byte[] input;
        private int inputPos;
        private int inputEnd;
        private uint range;
        private uint code;

        public static void Decompress(byte[] source, int sourceOffset, int sourceLength, byte[] destination, int destinationOffset, int destinationLength)
        {
            new WPFMAVrcaLzma().Run(source, sourceOffset, sourceLength, destination, destinationOffset, destinationLength);
        }

        private void Run(byte[] source, int sourceOffset, int sourceLength, byte[] destination, int destinationOffset, int destinationLength)
        {
            if (sourceLength < 5)
                throw new FormatException("LZMA chunk is too short to hold a property header.");

            byte packed = source[sourceOffset];
            if (packed >= 9 * 5 * 5)
                throw new FormatException("LZMA property byte is out of range.");

            int lc = packed % 9;
            packed /= 9;
            int lp = packed % 5;
            int pb = packed / 5;

            ResetProbabilities(lc, lp);

            input = source;
            inputPos = sourceOffset + 5;
            inputEnd = sourceOffset + sourceLength;
            InitRangeDecoder();

            uint posStateMask = (1u << pb) - 1;
            uint literalPosMask = (1u << lp) - 1;

            uint state = 0;
            uint rep0 = 0, rep1 = 0, rep2 = 0, rep3 = 0;
            byte previousByte = 0;
            int written = 0;

            while (written < destinationLength)
            {
                uint posState = (uint)written & posStateMask;

                if (DecodeBit(isMatch, (int)((state << NumPosBitsMax) + posState)) == 0)
                {
                    int literalOffset = 0x300 * (int)((((uint)written & literalPosMask) << lc) + (uint)(previousByte >> (8 - lc)));

                    previousByte = state < 7
                        ? DecodeLiteral(literalOffset)
                        : DecodeMatchedLiteral(literalOffset, destination[destinationOffset + written - (int)rep0 - 1]);

                    destination[destinationOffset + written] = previousByte;
                    written++;
                    state = state < 4 ? 0 : (state < 10 ? state - 3 : state - 6);
                    continue;
                }

                uint length;

                if (DecodeBit(isRep, (int)state) == 1)
                {
                    if (written == 0)
                        throw new FormatException("LZMA stream opened with a repeated match.");

                    if (DecodeBit(isRepG0, (int)state) == 0)
                    {
                        if (DecodeBit(isRep0Long, (int)((state << NumPosBitsMax) + posState)) == 0)
                        {
                            state = state < 7 ? 9u : 11u;
                            previousByte = destination[destinationOffset + written - (int)rep0 - 1];
                            destination[destinationOffset + written] = previousByte;
                            written++;
                            continue;
                        }
                    }
                    else
                    {
                        uint distance;
                        if (DecodeBit(isRepG1, (int)state) == 0)
                        {
                            distance = rep1;
                        }
                        else
                        {
                            if (DecodeBit(isRepG2, (int)state) == 0)
                            {
                                distance = rep2;
                            }
                            else
                            {
                                distance = rep3;
                                rep3 = rep2;
                            }

                            rep2 = rep1;
                        }

                        rep1 = rep0;
                        rep0 = distance;
                    }

                    length = DecodeLength(repLenDecoder, posState) + MatchMinLen;
                    state = state < 7 ? 8u : 11u;
                }
                else
                {
                    rep3 = rep2;
                    rep2 = rep1;
                    rep1 = rep0;

                    length = DecodeLength(lenDecoder, posState) + MatchMinLen;
                    state = state < 7 ? 7u : 10u;

                    uint lenToPosState = length - MatchMinLen < NumLenToPosStates ? length - MatchMinLen : NumLenToPosStates - 1;
                    uint slot = BitTreeDecode(posSlot, (int)(lenToPosState << 6), 6);

                    if (slot >= StartPosModelIndex)
                    {
                        int directBits = (int)((slot >> 1) - 1);
                        rep0 = (2 | (slot & 1)) << directBits;

                        if (slot < EndPosModelIndex)
                            rep0 += BitTreeReverseDecode(posDecoders, (int)(rep0 - slot), directBits);
                        else
                            rep0 += (DecodeDirectBits(directBits - NumAlignBits) << NumAlignBits) + BitTreeReverseDecode(posAlign, 0, NumAlignBits);
                    }
                    else
                    {
                        rep0 = slot;
                    }

                    if (rep0 == 0xFFFFFFFF)
                        break;

                    if (rep0 >= (uint)written)
                        throw new FormatException("LZMA match distance points before the start of the chunk.");
                }

                if (written + length > destinationLength)
                    length = (uint)(destinationLength - written);

                int match = destinationOffset + written - (int)rep0 - 1;
                for (uint i = 0; i < length; i++)
                    destination[destinationOffset + written++] = destination[match++];

                previousByte = destination[destinationOffset + written - 1];
            }

            if (written != destinationLength)
                throw new FormatException("LZMA chunk produced " + written + " bytes but " + destinationLength + " were expected.");
        }

        private void ResetProbabilities(int lc, int lp)
        {
            Fill(isMatch);
            Fill(isRep);
            Fill(isRepG0);
            Fill(isRepG1);
            Fill(isRepG2);
            Fill(isRep0Long);
            Fill(posSlot);
            Fill(posDecoders);
            Fill(posAlign);
            lenDecoder.Reset();
            repLenDecoder.Reset();

            int literalStates = 1 << (lc + lp);
            if (literalProbs == null || literalProbs.Length != literalStates * 0x300)
                literalProbs = new ushort[literalStates * 0x300];
            Fill(literalProbs);
        }

        private static void Fill(ushort[] probabilities)
        {
            for (int i = 0; i < probabilities.Length; i++)
                probabilities[i] = (ushort)ProbInit;
        }

        private byte NextByte()
        {
            return inputPos < inputEnd ? input[inputPos++] : (byte)0;
        }

        private void InitRangeDecoder()
        {
            range = 0xFFFFFFFF;
            code = 0;
            NextByte();
            for (int i = 0; i < 4; i++)
                code = (code << 8) | NextByte();
        }

        private uint DecodeBit(ushort[] probabilities, int index)
        {
            uint probability = probabilities[index];
            uint bound = (range >> BitModelTotalBits) * probability;
            uint bit;

            if (code < bound)
            {
                range = bound;
                probabilities[index] = (ushort)(probability + ((BitModelTotal - probability) >> MoveBits));
                bit = 0;
            }
            else
            {
                range -= bound;
                code -= bound;
                probabilities[index] = (ushort)(probability - (probability >> MoveBits));
                bit = 1;
            }

            if (range < TopValue)
            {
                code = (code << 8) | NextByte();
                range <<= 8;
            }

            return bit;
        }

        private uint DecodeDirectBits(int count)
        {
            uint result = 0;

            for (int i = count; i > 0; i--)
            {
                range >>= 1;
                uint t = (code - range) >> 31;
                code -= range & (t - 1);
                result = (result << 1) | (1 - t);

                if (range < TopValue)
                {
                    code = (code << 8) | NextByte();
                    range <<= 8;
                }
            }

            return result;
        }

        private uint BitTreeDecode(ushort[] probabilities, int offset, int levels)
        {
            uint m = 1;
            for (int i = levels; i > 0; i--)
                m = (m << 1) + DecodeBit(probabilities, offset + (int)m);

            return m - (1u << levels);
        }

        private uint BitTreeReverseDecode(ushort[] probabilities, int offset, int levels)
        {
            uint m = 1;
            uint symbol = 0;

            for (int i = 0; i < levels; i++)
            {
                uint bit = DecodeBit(probabilities, offset + (int)m);
                m = (m << 1) + bit;
                symbol |= bit << i;
            }

            return symbol;
        }

        private uint DecodeLength(LenDecoder decoder, uint posState)
        {
            if (DecodeBit(decoder.Choice, 0) == 0)
                return BitTreeDecode(decoder.Low, (int)(posState << 3), 3);

            if (DecodeBit(decoder.Choice, 1) == 0)
                return 8 + BitTreeDecode(decoder.Mid, (int)(posState << 3), 3);

            return 16 + BitTreeDecode(decoder.High, 0, 8);
        }

        private byte DecodeLiteral(int offset)
        {
            uint symbol = 1;
            do
            {
                symbol = (symbol << 1) | DecodeBit(literalProbs, offset + (int)symbol);
            }
            while (symbol < 0x100);

            return (byte)symbol;
        }

        private byte DecodeMatchedLiteral(int offset, byte matchByte)
        {
            uint symbol = 1;

            do
            {
                uint matchBit = (uint)(matchByte >> 7) & 1;
                matchByte <<= 1;

                uint bit = DecodeBit(literalProbs, offset + (int)(((1 + matchBit) << 8) + symbol));
                symbol = (symbol << 1) | bit;

                if (matchBit != bit)
                {
                    while (symbol < 0x100)
                        symbol = (symbol << 1) | DecodeBit(literalProbs, offset + (int)symbol);
                    break;
                }
            }
            while (symbol < 0x100);

            return (byte)symbol;
        }
    }
}
#endif
