// 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.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace WPFMA.Vrca
{
    [InitializeOnLoad]
    internal static class WPFMABundleShaders
    {
        internal enum State
        {
            Missing,
            CloseMatch,
            Installed
        }

        internal sealed class Need
        {
            public string Family;
            public string FirstName;
            public int Variants;
            public State State;
            public string Match;
            public string Version;
            public string HaveVersion;

            public bool VersionDiffers
            {
                get
                {
                    return !string.IsNullOrEmpty(Version) && !string.IsNullOrEmpty(HaveVersion) &&
                           MajorMinor(Version) != MajorMinor(HaveVersion);
                }
            }
        }

        internal sealed class Found
        {
            public string Name;
            public string Version;
        }

        /// <summary>Everything one read of a bundle gives the ripper's file panel: its shaders and the systems it was built with.</summary>
        internal sealed class BundleScan
        {
            public List<Found> Shaders;
            public List<WPFMABundleSystems.Found> Systems;
        }

        private const int ShaderClassId = 48;
        private const string VersionLabelProperty = "shader_master_label";

        private static readonly Regex ScriptName = new Regex("Shader\\s*\"([^\"]+)\"", RegexOptions.Compiled);
        private static readonly Regex ScriptVersionLabel =
            new Regex(VersionLabelProperty + "\\s*\\(\\s*\"([^\"]*)\"", RegexOptions.Compiled);
        private static readonly Regex VersionNumber = new Regex("\\d+(?:\\.\\d+)+", RegexOptions.Compiled);
        private static readonly Regex RichTextTag = new Regex("<[^>]*>", RegexOptions.Compiled);

        private static readonly System.Threading.SemaphoreSlim ScanSlots = new System.Threading.SemaphoreSlim(2);

        internal static int ProjectVersion { get; private set; }

        static WPFMABundleShaders()
        {
            EditorApplication.projectChanged += () => ProjectVersion++;
        }

        internal static BundleScan ReadNames(string bundlePath)
        {
            ScanSlots.Wait();
            try
            {
                return Scan(bundlePath);
            }
            finally
            {
                ScanSlots.Release();
            }
        }

        private static BundleScan Scan(string bundlePath)
        {
            var found = new SortedDictionary<string, Found>(StringComparer.Ordinal);
            var traces = new WPFMABundleSystems.Traces();

            using (var stream = File.OpenRead(bundlePath))
            {
                var bundle = WPFMAVrcaBundle.Open(stream);
                if (bundle.UsesContentEncryption)
                    throw new WPFMAVrcaException("The bundle is encrypted.");

                var serialized = bundle.Nodes.Where(n => (n.Flags & 4) != 0).ToList();
                if (serialized.Count == 0)
                    serialized = bundle.Nodes.Where(n => !IsResourceFile(n.Path)).ToList();

                foreach (var node in serialized)
                {
                    WPFMASerializedFile cab;
                    try
                    {
                        cab = WPFMASerializedFile.Parse(bundle.ExtractNodeBytes(stream, node));
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    foreach (var info in cab.Objects)
                    {
                        if (info.Type == null || info.Type.ClassId != ShaderClassId)
                            continue;

                        string script;
                        string name = NameOf(cab, info, out script);
                        if (string.IsNullOrEmpty(name) || found.ContainsKey(name))
                            continue;

                        found.Add(name, new Found { Name = name, Version = VersionOf(cab, info, script) });
                    }

                    WPFMABundleSystems.Collect(cab, traces);
                }
            }

            traces.Shaders.AddRange(found.Keys);
            return new BundleScan { Shaders = found.Values.ToList(), Systems = WPFMABundleSystems.Detect(traces) };
        }

        internal static List<Need> Classify(IEnumerable<Found> shaders, out int builtIn)
        {
            builtIn = 0;
            var byFamily = new Dictionary<string, Need>(StringComparer.OrdinalIgnoreCase);
            List<Shader> installed = null;

            foreach (var shader in shaders)
            {
                string name = shader.Name;

                if (name.StartsWith("Hidden/", StringComparison.OrdinalIgnoreCase) && WPFMAShaderFetch.IsBuiltIn(name))
                    continue;

                if (WPFMAShaderFetch.IsBuiltIn(name) || IsUnityResource(Shader.Find(name)))
                {
                    builtIn++;
                    continue;
                }

                string family = WPFMAShaderResolver.RecoverBaseName(name);
                if (string.IsNullOrEmpty(family))
                    family = name;

                Need need;
                if (byFamily.TryGetValue(family, out need))
                {
                    need.Variants++;
                    if (string.IsNullOrEmpty(need.Version))
                        need.Version = shader.Version;
                    continue;
                }

                need = new Need
                {
                    Family = family,
                    FirstName = name,
                    Variants = 1,
                    State = State.Missing,
                    Version = shader.Version
                };
                byFamily.Add(family, need);

                var have = ProjectShader(name) ?? ProjectShader(family);
                if (have != null)
                {
                    need.State = State.Installed;
                    need.HaveVersion = InstalledVersion(have);
                    continue;
                }

                if (installed == null)
                    installed = WPFMAShaderFetch.InstalledShaders().Where(InProject).ToList();

                string reason;
                var match = WPFMAShaderResolver.FindFamilyMatch(name, installed, out reason);
                if (match != null)
                {
                    need.State = State.CloseMatch;
                    need.Match = match.name;
                    need.HaveVersion = InstalledVersion(match);
                }
            }

            return byFamily.Values
                .OrderBy(n => n.State)
                .ThenBy(n => n.Family, StringComparer.OrdinalIgnoreCase)
                .ToList();
        }

        private static string NameOf(WPFMASerializedFile cab, WPFMASerializedFile.ObjectInfo info, out string script)
        {
            string name = null;
            script = null;

            try
            {
                name = cab.ReadString(info, "m_ParsedForm", "m_Name");
                if (!string.IsNullOrEmpty(name))
                    return name;

                name = cab.ReadString(info, "m_Name");
                script = cab.ReadString(info, "m_Script");

                if (!string.IsNullOrEmpty(name))
                    return name;

                if (!string.IsNullOrEmpty(script))
                {
                    var found = ScriptName.Match(script);
                    if (found.Success)
                        return found.Groups[1].Value;
                }
            }
            catch (Exception)
            {
            }

            return name;
        }

        private static string VersionOf(WPFMASerializedFile cab, WPFMASerializedFile.ObjectInfo info, string script)
        {
            try
            {
                if (!string.IsNullOrEmpty(script))
                {
                    var label = ScriptVersionLabel.Match(script);
                    return label.Success ? CleanVersion(label.Groups[1].Value) : null;
                }

                var propInfo = cab.ReadField(info, "m_ParsedForm", "m_PropInfo") as Dictionary<string, object>;
                object props;
                if (propInfo == null || !propInfo.TryGetValue("m_Props", out props) || !(props is List<object>))
                    return null;

                foreach (var item in (List<object>)props)
                {
                    var prop = item as Dictionary<string, object>;
                    object propName;
                    object description;
                    if (prop != null && prop.TryGetValue("m_Name", out propName) &&
                        VersionLabelProperty.Equals(propName as string) &&
                        prop.TryGetValue("m_Description", out description))
                        return CleanVersion(description as string);
                }
            }
            catch (Exception)
            {
            }

            return null;
        }

        private static string InstalledVersion(Shader shader)
        {
            try
            {
                int index = shader.FindPropertyIndex(VersionLabelProperty);
                return index >= 0 ? CleanVersion(shader.GetPropertyDescription(index)) : null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static string CleanVersion(string label)
        {
            if (string.IsNullOrEmpty(label))
                return null;

            var number = VersionNumber.Match(RichTextTag.Replace(label, string.Empty));
            return number.Success ? number.Value : null;
        }

        private static string MajorMinor(string version)
        {
            var parts = version.Split('.');
            return parts.Length >= 2 ? parts[0] + "." + parts[1] : version;
        }

        private static Shader ProjectShader(string name)
        {
            var shader = Shader.Find(name);
            return InProject(shader) ? shader : null;
        }

        private static bool InProject(Shader shader)
        {
            return shader != null && !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(shader));
        }

        private static bool IsUnityResource(Shader shader)
        {
            if (shader == null)
                return false;

            string path = AssetDatabase.GetAssetPath(shader);
            return path.StartsWith("Resources/", StringComparison.Ordinal) ||
                   path.StartsWith("Library/", StringComparison.Ordinal);
        }

        private static bool IsResourceFile(string path)
        {
            return path.EndsWith(".resS", StringComparison.OrdinalIgnoreCase) ||
                   path.EndsWith(".resource", StringComparison.OrdinalIgnoreCase);
        }
    }
}
#endif
