// 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;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

namespace WPFMA.Vrca
{
    public enum WPFMAVrcaCompression
    {
        None = 0,
        Lzma = 1,
        Lz4 = 2,
        Lz4Hc = 3,
        Lzham = 4
    }

    public sealed class WPFMAVrcaBlock
    {
        public uint UncompressedSize;
        public uint CompressedSize;
        public ushort Flags;

        public WPFMAVrcaCompression Compression
        {
            get { return (WPFMAVrcaCompression)(Flags & 0x3F); }
        }
    }

    public sealed class WPFMAVrcaNode
    {
        public long Offset;
        public long Size;
        public uint Flags;
        public string Path;
    }

    public sealed class WPFMAVrcaBundle
    {
        private const int FlagBlocksAndDirectoryInfoCombined = 0x40;
        private const int FlagBlocksInfoAtTheEnd = 0x80;
        private const int FlagBlockInfoNeedPaddingAtStart = 0x200;
        private const int FlagContentEncryption = 0x400;

        private const int MaxNodes = 4096;
        private const int MaxBlocks = 1 << 20;

        public string Signature { get; private set; }
        public int FormatVersion { get; private set; }
        public string MinimumUnityVersion { get; private set; }
        public string UnityRevision { get; private set; }
        public long DeclaredSize { get; private set; }
        public int Flags { get; private set; }
        public long DataOffset { get; private set; }
        public List<WPFMAVrcaBlock> Blocks { get; private set; }
        public List<WPFMAVrcaNode> Nodes { get; private set; }

        public bool IsLegacy { get; private set; }

        private byte[] legacyPayload;

        public bool UsesContentEncryption
        {
            get { return (Flags & FlagContentEncryption) != 0; }
        }

        public WPFMAVrcaCompression BlocksInfoCompression
        {
            get { return (WPFMAVrcaCompression)(Flags & 0x3F); }
        }

        public long TotalUncompressedSize
        {
            get
            {
                long total = 0;
                foreach (var block in Blocks)
                    total += block.UncompressedSize;
                return total;
            }
        }

        public static WPFMAVrcaBundle Open(Stream stream)
        {
            var bundle = new WPFMAVrcaBundle();
            var reader = new BigEndianReader(stream);

            bundle.Signature = reader.ReadCString(32);
            if (bundle.Signature == "UnityWeb" || bundle.Signature == "UnityRaw")
            {
                OpenLegacy(bundle, reader, stream);
                return bundle;
            }

            if (bundle.Signature != "UnityFS")
                throw new WPFMAVrcaException("Not a Unity asset bundle: expected a UnityFS signature.");

            bundle.FormatVersion = reader.ReadInt32();
            if (bundle.FormatVersion < 6 || bundle.FormatVersion > 8)
                throw new WPFMAVrcaException("Unsupported UnityFS format version " + bundle.FormatVersion + ".");

            bundle.MinimumUnityVersion = reader.ReadCString(64);
            bundle.UnityRevision = reader.ReadCString(64);
            bundle.DeclaredSize = reader.ReadInt64();

            int compressedTableSize = reader.ReadInt32();
            int uncompressedTableSize = reader.ReadInt32();
            bundle.Flags = reader.ReadInt32();

            if (bundle.FormatVersion >= 7)
                reader.Align(16);

            if (bundle.UsesContentEncryption)
            {
                bundle.Blocks = new List<WPFMAVrcaBlock>();
                bundle.Nodes = new List<WPFMAVrcaNode>();
                return bundle;
            }

            if (compressedTableSize <= 0 || uncompressedTableSize <= 0 || uncompressedTableSize > (1 << 26))
                throw new WPFMAVrcaException("The archive directory has an implausible size; the file is truncated or not a plain UnityFS archive.");

            byte[] compressedTable = new byte[compressedTableSize];

            if ((bundle.Flags & FlagBlocksInfoAtTheEnd) != 0)
            {
                long resume = stream.Position;
                long end = bundle.DeclaredSize > 0 && bundle.DeclaredSize <= stream.Length ? bundle.DeclaredSize : stream.Length;
                stream.Position = end - compressedTableSize;
                reader.ReadExactly(compressedTable, 0, compressedTableSize);
                stream.Position = resume;
            }
            else
            {
                reader.ReadExactly(compressedTable, 0, compressedTableSize);
                if ((bundle.Flags & FlagBlockInfoNeedPaddingAtStart) != 0)
                    reader.Align(16);
            }

            bundle.DataOffset = stream.Position;

            byte[] table = Decompress(compressedTable, 0, compressedTableSize, uncompressedTableSize, bundle.BlocksInfoCompression, "archive directory");
            bundle.ReadTables(table);
            return bundle;
        }

        private void ReadTables(byte[] table)
        {
            var reader = new BigEndianReader(new MemoryStream(table, false));
            reader.Skip(16);

            int blockCount = reader.ReadInt32();
            if (blockCount < 0 || blockCount > MaxBlocks)
                throw new WPFMAVrcaException("The archive reports an implausible block count (" + blockCount + ").");

            Blocks = new List<WPFMAVrcaBlock>(blockCount);
            for (int i = 0; i < blockCount; i++)
            {
                Blocks.Add(new WPFMAVrcaBlock
                {
                    UncompressedSize = (uint)reader.ReadInt32(),
                    CompressedSize = (uint)reader.ReadInt32(),
                    Flags = (ushort)reader.ReadInt16()
                });
            }

            int nodeCount = reader.ReadInt32();
            if (nodeCount < 0 || nodeCount > MaxNodes)
                throw new WPFMAVrcaException("The archive reports an implausible file count (" + nodeCount + ").");

            Nodes = new List<WPFMAVrcaNode>(nodeCount);
            for (int i = 0; i < nodeCount; i++)
            {
                var node = new WPFMAVrcaNode
                {
                    Offset = reader.ReadInt64(),
                    Size = reader.ReadInt64(),
                    Flags = (uint)reader.ReadInt32()
                };
                node.Path = reader.ReadCString(512);
                Nodes.Add(node);
            }

            long total = TotalUncompressedSize;
            foreach (var node in Nodes)
            {
                if (node.Offset < 0 || node.Size < 0 || node.Offset + node.Size > total)
                    throw new WPFMAVrcaException("File '" + node.Path + "' falls outside the archive data stream.");
            }
        }

        private static void OpenLegacy(WPFMAVrcaBundle bundle, BigEndianReader reader, Stream stream)
        {
            bundle.IsLegacy = true;
            bundle.Blocks = new List<WPFMAVrcaBlock>();
            bundle.Nodes = new List<WPFMAVrcaNode>();

            bundle.FormatVersion = reader.ReadInt32();
            if (bundle.FormatVersion < 1 || bundle.FormatVersion > 6)
                throw new WPFMAVrcaException("Unsupported " + bundle.Signature + " stream version " + bundle.FormatVersion + ".");

            bundle.MinimumUnityVersion = reader.ReadCString(64);
            bundle.UnityRevision = reader.ReadCString(64);

            reader.ReadInt32();
            int headerSize = reader.ReadInt32();
            if (headerSize <= 0 || headerSize > stream.Length)
                throw new WPFMAVrcaException("The archive header size is implausible; the file is truncated.");

            reader.ReadInt32();
            int levelCount = reader.ReadInt32();
            if (levelCount < 0 || levelCount > 1024)
                throw new WPFMAVrcaException("The archive declares " + levelCount + " levels, which is not plausible.");

            int compressedSize = 0;
            int uncompressedSize = 0;
            for (int i = 0; i < levelCount; i++)
            {
                compressedSize = reader.ReadInt32();
                uncompressedSize = reader.ReadInt32();
            }

            if (compressedSize <= 0 || uncompressedSize <= 0)
                throw new WPFMAVrcaException("The archive declares an empty payload.");

            if (uncompressedSize > (1 << 30))
                throw new WPFMAVrcaException("The archive payload is over 1 GB uncompressed, which this reader will not hold in memory.");

            long available = stream.Length - headerSize;
            if (compressedSize > available)
                compressedSize = (int)available;

            stream.Position = headerSize;

            byte[] payload;
            if (bundle.Signature == "UnityRaw")
            {
                payload = new byte[uncompressedSize];
                reader.ReadExactly(payload, 0, Math.Min(uncompressedSize, (int)available));
            }
            else
            {
                var compressed = new byte[compressedSize];
                reader.ReadExactly(compressed, 0, compressedSize);
                payload = DecompressLzmaAlone(compressed, uncompressedSize);
            }

            bundle.legacyPayload = payload;
            bundle.DataOffset = headerSize;
            ReadLegacyFileTable(bundle, payload);
        }

        private static byte[] DecompressLzmaAlone(byte[] compressed, int uncompressedSize)
        {
            const int propertiesSize = 5;
            const int lengthSize = 8;

            if (compressed.Length < propertiesSize + lengthSize)
                throw new WPFMAVrcaException("The compressed payload is too short to be an LZMA stream.");

            long declared = 0;
            for (int i = lengthSize - 1; i >= 0; i--)
                declared = (declared << 8) | compressed[propertiesSize + i];

            int size = uncompressedSize;
            if (declared > 0 && declared < size)
                size = (int)declared;

            var joined = new byte[compressed.Length - lengthSize];
            Array.Copy(compressed, 0, joined, 0, propertiesSize);
            Array.Copy(compressed, propertiesSize + lengthSize, joined, propertiesSize,
                compressed.Length - propertiesSize - lengthSize);

            var plain = new byte[size];
            WPFMAVrcaLzma.Decompress(joined, 0, joined.Length, plain, 0, size);
            return plain;
        }

        private static void ReadLegacyFileTable(WPFMAVrcaBundle bundle, byte[] payload)
        {
            int position = 0;
            int fileCount = ReadPayloadInt32(payload, ref position);
            if (fileCount < 0 || fileCount > MaxNodes)
                throw new WPFMAVrcaException("The archive declares " + fileCount + " files, which is not plausible.");

            for (int i = 0; i < fileCount; i++)
            {
                string name = ReadPayloadCString(payload, ref position);
                int offset = ReadPayloadInt32(payload, ref position);
                int size = ReadPayloadInt32(payload, ref position);

                if (offset < 0 || size < 0 || (long)offset + size > payload.Length)
                    throw new WPFMAVrcaException("File '" + name + "' points outside the archive payload.");

                bundle.Nodes.Add(new WPFMAVrcaNode
                {
                    Path = string.IsNullOrEmpty(name) ? "file" + i : name,
                    Offset = offset,
                    Size = size,
                    Flags = 0
                });
            }
        }

        private static int ReadPayloadInt32(byte[] payload, ref int position)
        {
            if (position + 4 > payload.Length)
                throw new WPFMAVrcaException("The archive payload ended while reading its file table.");

            int value = (payload[position] << 24) | (payload[position + 1] << 16) |
                        (payload[position + 2] << 8) | payload[position + 3];
            position += 4;
            return value;
        }

        private static string ReadPayloadCString(byte[] payload, ref int position)
        {
            var builder = new StringBuilder();
            while (position < payload.Length)
            {
                byte b = payload[position++];
                if (b == 0)
                    return builder.ToString();

                builder.Append((char)b);
                if (builder.Length > 512)
                    throw new WPFMAVrcaException("A file name in the archive is unreasonably long.");
            }

            throw new WPFMAVrcaException("The archive payload ended inside a file name.");
        }

        private List<string> ExtractLegacy(string outputDirectory, Func<float, string, bool> onProgress)
        {
            Directory.CreateDirectory(outputDirectory);
            var written = new List<string>(Nodes.Count);

            for (int i = 0; i < Nodes.Count; i++)
            {
                var node = Nodes[i];

                if (onProgress != null && !onProgress(i / (float)Math.Max(1, Nodes.Count), "File " + (i + 1) + " of " + Nodes.Count))
                    throw new OperationCanceledException();

                string path = ResolveOutputPath(outputDirectory, node.Path);
                Directory.CreateDirectory(Path.GetDirectoryName(path));

                using (var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))
                    output.Write(legacyPayload, (int)node.Offset, (int)node.Size);

                written.Add(path);
            }

            if (onProgress != null)
                onProgress(1f, "Done");

            return written;
        }

        public void WritePayload(Stream source, Stream destination)
        {
            if (UsesContentEncryption)
                throw new WPFMAVrcaException("This bundle is encrypted; its contents cannot be read.");

            if (IsLegacy)
            {
                destination.Write(legacyPayload, 0, legacyPayload.Length);
                return;
            }

            int maxUncompressed = 0;
            int maxCompressed = 0;
            foreach (var block in Blocks)
            {
                if (block.UncompressedSize > maxUncompressed)
                    maxUncompressed = (int)block.UncompressedSize;
                if (block.CompressedSize > maxCompressed)
                    maxCompressed = (int)block.CompressedSize;
            }

            byte[] compressed = new byte[maxCompressed];
            byte[] plain = new byte[maxUncompressed];

            source.Position = DataOffset;
            var reader = new BigEndianReader(source);

            for (int i = 0; i < Blocks.Count; i++)
            {
                var block = Blocks[i];
                reader.ReadExactly(compressed, 0, (int)block.CompressedSize);

                if (block.Compression == WPFMAVrcaCompression.None)
                {
                    if (block.CompressedSize != block.UncompressedSize)
                        throw new WPFMAVrcaException("Block " + i + " is stored uncompressed but its two sizes disagree.");

                    destination.Write(compressed, 0, (int)block.UncompressedSize);
                    continue;
                }

                DecompressInto(compressed, 0, (int)block.CompressedSize, plain, (int)block.UncompressedSize,
                    block.Compression, "block " + i);
                destination.Write(plain, 0, (int)block.UncompressedSize);
            }
        }

        public List<string> Extract(Stream stream, string outputDirectory, Func<float, string, bool> onProgress)
        {
            if (UsesContentEncryption)
                throw new WPFMAVrcaException("This bundle is encrypted; its contents cannot be read.");
            if (Nodes.Count == 0)
                throw new WPFMAVrcaException("The archive contains no files.");

            if (IsLegacy)
                return ExtractLegacy(outputDirectory, onProgress);

            Directory.CreateDirectory(outputDirectory);

            int maxUncompressed = 0;
            int maxCompressed = 0;
            foreach (var block in Blocks)
            {
                if (block.UncompressedSize > maxUncompressed)
                    maxUncompressed = (int)block.UncompressedSize;
                if (block.CompressedSize > maxCompressed)
                    maxCompressed = (int)block.CompressedSize;
            }

            byte[] compressed = new byte[maxCompressed];
            byte[] plain = new byte[maxUncompressed];

            var written = new List<string>(Nodes.Count);
            var outputs = new List<FileStream>(Nodes.Count);

            try
            {
                foreach (var node in Nodes)
                {
                    string path = ResolveOutputPath(outputDirectory, node.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    outputs.Add(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16));
                    written.Add(path);
                }

                stream.Position = DataOffset;
                var reader = new BigEndianReader(stream);
                long total = TotalUncompressedSize;
                long streamPosition = 0;

                for (int i = 0; i < Blocks.Count; i++)
                {
                    var block = Blocks[i];

                    if (onProgress != null && !onProgress((float)((double)streamPosition / Math.Max(1, total)),
                            "Block " + (i + 1) + " of " + Blocks.Count))
                        throw new OperationCanceledException();

                    reader.ReadExactly(compressed, 0, (int)block.CompressedSize);

                    byte[] source;
                    int sourceOffset;
                    if (block.Compression == WPFMAVrcaCompression.None)
                    {
                        source = compressed;
                        sourceOffset = 0;
                        if (block.CompressedSize != block.UncompressedSize)
                            throw new WPFMAVrcaException("Block " + i + " is stored uncompressed but its two sizes disagree.");
                    }
                    else
                    {
                        DecompressInto(compressed, 0, (int)block.CompressedSize, plain, (int)block.UncompressedSize, block.Compression, "block " + i);
                        source = plain;
                        sourceOffset = 0;
                    }

                    long blockStart = streamPosition;
                    long blockEnd = streamPosition + block.UncompressedSize;

                    for (int n = 0; n < Nodes.Count; n++)
                    {
                        var node = Nodes[n];
                        long from = Math.Max(blockStart, node.Offset);
                        long to = Math.Min(blockEnd, node.Offset + node.Size);
                        if (to <= from)
                            continue;

                        var output = outputs[n];
                        output.Position = from - node.Offset;
                        output.Write(source, sourceOffset + (int)(from - blockStart), (int)(to - from));
                    }

                    streamPosition = blockEnd;
                }
            }
            finally
            {
                foreach (var output in outputs)
                    output.Dispose();
            }

            WriteRipReport(stream, outputDirectory);
            return written;
        }

        private static void WriteRipReport(Stream stream, string outputDirectory)
        {
            var fileStream = stream as FileStream;
            if (fileStream == null)
                return;

            string source = fileStream.Name;

            try
            {
                string written = WPFMARipReport.Generate(source,
                    Path.Combine(outputDirectory, "export report.txt"), null,
                    WPFMAVrcaPreview.GetLoadedBundle(source));

                Debug.Log("[WPFMA-SDK] Export report: " + written);
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not write the export report for " +
                                 Path.GetFileName(source) + ": " + e.Message);
            }
        }

        public byte[] ExtractNodeBytes(Stream stream, WPFMAVrcaNode node)
        {
            if (UsesContentEncryption)
                throw new WPFMAVrcaException("This bundle is encrypted; its contents cannot be read.");
            if (node.Size > int.MaxValue)
                throw new WPFMAVrcaException("The requested file is too large to hold in memory.");

            var result = new byte[node.Size];
            long nodeEnd = node.Offset + node.Size;

            int maxUncompressed = 0;
            int maxCompressed = 0;
            foreach (var block in Blocks)
            {
                if (block.UncompressedSize > maxUncompressed)
                    maxUncompressed = (int)block.UncompressedSize;
                if (block.CompressedSize > maxCompressed)
                    maxCompressed = (int)block.CompressedSize;
            }

            byte[] compressed = new byte[maxCompressed];
            byte[] plain = new byte[maxUncompressed];

            stream.Position = DataOffset;
            var reader = new BigEndianReader(stream);
            long position = 0;

            foreach (var block in Blocks)
            {
                long blockEnd = position + block.UncompressedSize;

                if (blockEnd <= node.Offset)
                {
                    stream.Position += block.CompressedSize;
                    position = blockEnd;
                    continue;
                }

                if (position >= nodeEnd)
                    break;

                reader.ReadExactly(compressed, 0, (int)block.CompressedSize);

                byte[] sourceBytes;
                if (block.Compression == WPFMAVrcaCompression.None)
                {
                    sourceBytes = compressed;
                }
                else
                {
                    DecompressInto(compressed, 0, (int)block.CompressedSize, plain, (int)block.UncompressedSize,
                        block.Compression, "block");
                    sourceBytes = plain;
                }

                long from = Math.Max(position, node.Offset);
                long to = Math.Min(blockEnd, nodeEnd);
                Buffer.BlockCopy(sourceBytes, (int)(from - position), result, (int)(from - node.Offset), (int)(to - from));

                position = blockEnd;
            }

            return result;
        }

        private static void DecompressInto(byte[] source, int sourceOffset, int sourceLength, byte[] destination, int destinationLength, WPFMAVrcaCompression compression, string what)
        {
            try
            {
                switch (compression)
                {
                    case WPFMAVrcaCompression.Lzma:
                        WPFMAVrcaLzma.Decompress(source, sourceOffset, sourceLength, destination, 0, destinationLength);
                        return;

                    case WPFMAVrcaCompression.Lz4:
                    case WPFMAVrcaCompression.Lz4Hc:
                        int produced = WPFMAVrcaLz4.Decompress(source, sourceOffset, sourceLength, destination, 0, destinationLength);
                        if (produced != destinationLength)
                            throw new FormatException("LZ4 produced " + produced + " bytes but " + destinationLength + " were expected.");
                        return;

                    case WPFMAVrcaCompression.Lzham:
                        throw new WPFMAVrcaException("The " + what + " uses LZHAM compression, which is not supported.");

                    default:
                        throw new WPFMAVrcaException("The " + what + " uses unknown compression type " + (int)compression + ".");
                }
            }
            catch (Exception e) when (e is FormatException || e is IndexOutOfRangeException)
            {
                throw new WPFMAVrcaException("Could not decompress the " + what + ": " + e.Message +
                    " The file may be damaged, incomplete, or not a plain UnityFS archive.");
            }
        }

        private static byte[] Decompress(byte[] source, int sourceOffset, int sourceLength, int destinationLength, WPFMAVrcaCompression compression, string what)
        {
            if (compression == WPFMAVrcaCompression.None)
            {
                if (sourceLength != destinationLength)
                    throw new WPFMAVrcaException("The " + what + " is stored uncompressed but its two sizes disagree.");

                var copy = new byte[destinationLength];
                Buffer.BlockCopy(source, sourceOffset, copy, 0, destinationLength);
                return copy;
            }

            var result = new byte[destinationLength];
            DecompressInto(source, sourceOffset, sourceLength, result, destinationLength, compression, what);
            return result;
        }

        private static string ResolveOutputPath(string outputDirectory, string nodePath)
        {
            if (string.IsNullOrEmpty(nodePath))
                nodePath = "unnamed";

            var segments = nodePath.Split('/', '\\');
            var safe = new List<string>(segments.Length);

            foreach (var segment in segments)
            {
                if (segment.Length == 0 || segment == "." || segment == "..")
                    continue;

                var builder = new StringBuilder(segment.Length);
                foreach (char c in segment)
                    builder.Append(c < 32 || c == ':' || c == '*' || c == '?' || c == '"' || c == '<' || c == '>' || c == '|' ? '_' : c);

                safe.Add(builder.ToString());
            }

            if (safe.Count == 0)
                safe.Add("unnamed");

            return Path.Combine(outputDirectory, Path.Combine(safe.ToArray()));
        }

        private sealed class BigEndianReader
        {
            private readonly Stream stream;
            private readonly byte[] scratch = new byte[8];

            public BigEndianReader(Stream stream)
            {
                this.stream = stream;
            }

            public void ReadExactly(byte[] buffer, int offset, int count)
            {
                int read = 0;
                while (read < count)
                {
                    int step = stream.Read(buffer, offset + read, count - read);
                    if (step <= 0)
                        throw new WPFMAVrcaException("The file ends earlier than its header says; it is truncated or still downloading.");
                    read += step;
                }
            }

            public void Skip(int count)
            {
                stream.Position += count;
            }

            public void Align(int alignment)
            {
                long remainder = stream.Position % alignment;
                if (remainder != 0)
                    stream.Position += alignment - remainder;
            }

            public short ReadInt16()
            {
                ReadExactly(scratch, 0, 2);
                return (short)((scratch[0] << 8) | scratch[1]);
            }

            public int ReadInt32()
            {
                ReadExactly(scratch, 0, 4);
                return (scratch[0] << 24) | (scratch[1] << 16) | (scratch[2] << 8) | scratch[3];
            }

            public long ReadInt64()
            {
                ReadExactly(scratch, 0, 8);
                long value = 0;
                for (int i = 0; i < 8; i++)
                    value = (value << 8) | scratch[i];
                return value;
            }

            public string ReadCString(int maxLength)
            {
                var builder = new StringBuilder();
                for (int i = 0; i < maxLength; i++)
                {
                    int b = stream.ReadByte();
                    if (b <= 0)
                        return builder.ToString();
                    builder.Append((char)b);
                }

                throw new WPFMAVrcaException("Malformed text field in the archive header.");
            }
        }
    }

    public sealed class WPFMAVrcaException : Exception
    {
        public WPFMAVrcaException(string message) : base(message)
        {
        }
    }
}
#endif
