// 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
{
    internal static class WPFMAVrcaRepack
    {
        private static string CacheRoot
        {
            get { return Path.Combine(Path.GetTempPath(), "WPFMA-SDK-repack"); }
        }

        internal static string ToLoadableCopy(string vrcaPath, out string message)
        {
            message = null;

            try
            {
                var source = new FileInfo(vrcaPath);
                if (!source.Exists)
                {
                    message = "That .vrca is no longer on disk.";
                    return null;
                }

                Directory.CreateDirectory(CacheRoot);

                string key = Hash(source.FullName) + "-" + WPFMAPaths.SafeFileName(Path.GetFileName(vrcaPath));
                string destination = Path.Combine(CacheRoot, key);

                var existing = new FileInfo(destination);
                if (existing.Exists && existing.LastWriteTimeUtc >= source.LastWriteTimeUtc && existing.Length > 0)
                    return destination;

                using (var input = File.OpenRead(vrcaPath))
                {
                    var bundle = WPFMAVrcaBundle.Open(input);

                    if (bundle.UsesContentEncryption)
                    {
                        message = "This bundle is encrypted, so its contents cannot be repacked.";
                        return null;
                    }

                    if (bundle.IsLegacy)
                    {
                        message = "This is a " + bundle.Signature + " archive, which Unity retired. Repacking it " +
                                  "would not make the loader accept it.";
                        return null;
                    }

                    if (bundle.Nodes.Count == 0)
                    {
                        message = "The archive contains no files.";
                        return null;
                    }

                    Write(bundle, input, destination);
                }

                return destination;
            }
            catch (WPFMAVrcaException e)
            {
                message = e.Message;
                return null;
            }
            catch (Exception e)
            {
                message = e.Message;
                Debug.LogWarning("[WPFMA-SDK] Could not repack " + Path.GetFileName(vrcaPath) + ": " + e);
                return null;
            }
        }

        internal static void ClearCache()
        {
            try
            {
                if (Directory.Exists(CacheRoot))
                    Directory.Delete(CacheRoot, true);
            }
            catch (Exception)
            {
            }
        }

        private static void Write(WPFMAVrcaBundle bundle, Stream input, string destination)
        {
            long payloadSize = bundle.TotalUncompressedSize;
            if (payloadSize <= 0 || payloadSize > int.MaxValue)
                throw new WPFMAVrcaException("The archive payload is " + payloadSize + " bytes, which cannot be repacked in one block.");

            byte[] directory = BuildDirectory(bundle, (int)payloadSize);

            var header = new MemoryStream();
            WriteCString(header, "UnityFS");
            WriteInt32(header, 6);
            WriteCString(header, string.IsNullOrEmpty(bundle.MinimumUnityVersion) ? "5.x.x" : bundle.MinimumUnityVersion);
            WriteCString(header, bundle.UnityRevision ?? string.Empty);

            long total = header.Length + 8 + 12 + directory.Length + payloadSize;
            WriteInt64(header, total);
            WriteInt32(header, directory.Length);
            WriteInt32(header, directory.Length);

            WriteInt32(header, 0x40);

            string temporary = destination + ".part";

            using (var output = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))
            {
                header.Position = 0;
                header.CopyTo(output);
                output.Write(directory, 0, directory.Length);

                bundle.WritePayload(input, output);

                if (output.Length != total)
                    throw new WPFMAVrcaException("The repacked archive came out " + output.Length +
                                                 " bytes when its header declares " + total + ".");
            }

            if (File.Exists(destination))
                File.Delete(destination);

            File.Move(temporary, destination);
        }

        private static byte[] BuildDirectory(WPFMAVrcaBundle bundle, int payloadSize)
        {
            var buffer = new MemoryStream();

            buffer.Write(new byte[16], 0, 16);

            WriteInt32(buffer, 1);
            WriteInt32(buffer, payloadSize);
            WriteInt32(buffer, payloadSize);
            WriteUInt16(buffer, 0);

            WriteInt32(buffer, bundle.Nodes.Count);
            foreach (var node in bundle.Nodes)
            {
                WriteInt64(buffer, node.Offset);
                WriteInt64(buffer, node.Size);
                WriteInt32(buffer, unchecked((int)node.Flags));
                WriteCString(buffer, node.Path);
            }

            return buffer.ToArray();
        }

        private static string Hash(string value)
        {
            unchecked
            {
                uint hash = 2166136261;
                foreach (var c in value.ToLowerInvariant())
                {
                    hash ^= c;
                    hash *= 16777619;
                }

                return hash.ToString("x8");
            }
        }

        private static void WriteCString(Stream stream, string value)
        {
            var bytes = Encoding.UTF8.GetBytes(value ?? string.Empty);
            stream.Write(bytes, 0, bytes.Length);
            stream.WriteByte(0);
        }

        private static void WriteUInt16(Stream stream, ushort value)
        {
            stream.WriteByte((byte)(value >> 8));
            stream.WriteByte((byte)value);
        }

        private static void WriteInt32(Stream stream, int value)
        {
            stream.WriteByte((byte)(value >> 24));
            stream.WriteByte((byte)(value >> 16));
            stream.WriteByte((byte)(value >> 8));
            stream.WriteByte((byte)value);
        }

        private static void WriteInt64(Stream stream, long value)
        {
            for (int shift = 56; shift >= 0; shift -= 8)
                stream.WriteByte((byte)(value >> shift));
        }
    }
}
#endif
