// 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;
using WPFMA.Vrca;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    public static class WPFMAVrcaSelfTest
    {
        private const string ExportFolder = "Assets/WPFMA-SDK/Rips/SelfTest";

        public static void Run()
        {
            string vrca = FindBundle();
            if (string.IsNullOrEmpty(vrca))
                return;

            string projectRoot = Directory.GetParent(Application.dataPath).FullName;
            string logPath = Path.Combine(projectRoot, "WPFMA_SelfTest.log");

            if (!EditorUtility.DisplayDialog("WPFMA-SDK VRCA Self-Test",
                    "This will:\n\n" +
                    "•  parse and extract " + Path.GetFileName(vrca) + "\n" +
                    "•  export it to " + ExportFolder + " (can be a few hundred MB of PNGs, and Unity will import them)\n" +
                    "•  write a report to WPFMA_SelfTest.log\n\n" +
                    "You can delete " + ExportFolder + " afterwards.\n\nRun it?",
                    "Run", "Cancel"))
                return;

            var log = new StringBuilder();
            void Line(string text)
            {
                log.AppendLine(text);
                Debug.Log("[WPFMA-SDK selftest] " + text);
            }

            Line("=== WPFMA-SDK VRCA self-test ===");
            Line("unity=" + Application.unityVersion + "  target=" + EditorUserBuildSettings.activeBuildTarget);
            Line("bundle=" + vrca);
            Line("");

            try
            {
                ReportEnvironment(Line);
                ReportBundle(vrca, Line);
                ReportExtract(vrca, projectRoot, Line);
                ReportExport(vrca, Line);
            }
            catch (Exception e)
            {
                Line("FATAL " + e.GetType().Name + ": " + e.Message);
                Line(e.StackTrace ?? string.Empty);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                File.WriteAllText(logPath, log.ToString());
                Debug.Log("[WPFMA-SDK selftest] report written to " + logPath);
                EditorUtility.RevealInFinder(logPath);
            }
        }

        private static string FindBundle()
        {
            var candidates = Directory.GetFiles(Application.dataPath, "*.vrca", SearchOption.AllDirectories);
            if (candidates.Length > 0)
                return candidates[0];

            string picked = EditorUtility.OpenFilePanel("Pick a .vrca for the self-test", string.Empty, "vrca");
            return string.IsNullOrEmpty(picked) ? null : picked;
        }

        private static void ReportEnvironment(Action<string> line)
        {
            line("--- shader environment ---");

            var interesting = new[] { "poiyomi", "liltoon", "unlit", "arktoon", "sunao" };
            var found = new List<string>();

            foreach (var info in ShaderUtil.GetAllShaderInfo())
            {
                string lowered = info.name.ToLowerInvariant();
                if (interesting.Any(lowered.Contains))
                    found.Add(info.name + (info.hasErrors ? "  [HAS ERRORS]" : string.Empty));
            }

            line("total shaders in project: " + ShaderUtil.GetAllShaderInfo().Length);
            line("avatar-shader families found: " + (found.Count == 0 ? "NONE" : found.Count.ToString()));
            foreach (var name in found.Take(25))
                line("   " + name);
            if (found.Count == 0)
                line("   (no Poiyomi/lilToon installed - material rebuild will fall back to Standard)");
            line("");
        }

        private static void ReportBundle(string vrca, Action<string> line)
        {
            line("--- container parse ---");
            using (var stream = File.OpenRead(vrca))
            {
                var bundle = WPFMAVrcaBundle.Open(stream);
                line("signature=" + bundle.Signature + " v" + bundle.FormatVersion +
                     " unity=" + bundle.UnityRevision + " flags=0x" + bundle.Flags.ToString("x"));
                line("encrypted=" + bundle.UsesContentEncryption +
                     " dirCompression=" + bundle.BlocksInfoCompression +
                     " blocks=" + bundle.Blocks.Count + " files=" + bundle.Nodes.Count);
                line("unpacked size=" + bundle.TotalUncompressedSize);

                var kinds = bundle.Blocks.Select(b => b.Compression).Distinct();
                line("block compression: " + string.Join(", ", kinds));

                foreach (var node in bundle.Nodes)
                    line("   node " + node.Path + "  " + node.Size + " bytes");
            }
            line("");
        }

        private static void ReportExtract(string vrca, string projectRoot, Action<string> line)
        {
            line("--- extract ---");
            string destination = Path.Combine(Path.Combine(projectRoot, "WPFMA_Rips"), "SelfTest");

            using (var stream = File.OpenRead(vrca))
            {
                var bundle = WPFMAVrcaBundle.Open(stream);
                var written = bundle.Extract(stream, destination, (fraction, status) =>
                    !EditorUtility.DisplayCancelableProgressBar("Self-test: extracting", status, fraction));

                foreach (var file in written)
                    line("   wrote " + Path.GetFileName(file) + "  " + new FileInfo(file).Length + " bytes");
            }

            EditorUtility.ClearProgressBar();
            line("extract OK -> " + destination);
            line("");
        }

        private static void ReportExport(string vrca, Action<string> line)
        {
            line("--- export to project assets ---");

            var report = WPFMAVrcaExporter.Export(vrca, ExportFolder, null, (fraction, status) =>
                !EditorUtility.DisplayCancelableProgressBar("Self-test: exporting", status, fraction));

            EditorUtility.ClearProgressBar();

            line("result: " + report.Summary);
            line("prefab: " + (report.PrefabPath ?? "<not written>"));
            line("missing scripts stripped: " + report.MissingScriptsStripped);
            line("");

            line("--- components carried onto the prefab ---");
            var vrchat = report.VrchatComponents.OrderByDescending(c => c.Value).ToList();
            line("VRChat components: " + (vrchat.Count == 0 ? "NONE RESOLVED" : string.Empty));
            foreach (var component in vrchat)
                line("   " + component.Key + " x" + component.Value);

            line("all components:");
            foreach (var component in report.Components.OrderByDescending(c => c.Value).Take(30))
                line("   " + component.Key + " x" + component.Value);

            if (report.MissingScriptPaths.Count > 0)
            {
                line("objects with unresolvable scripts (first 20):");
                foreach (var path in report.MissingScriptPaths.Distinct().Take(20))
                    line("   " + path);
            }

            line("");
            line("warnings: " + report.Warnings.Count);
            foreach (var warning in report.Warnings.Take(40))
                line("   ! " + warning);
            line("");

            if (string.IsNullOrEmpty(report.PrefabPath))
                return;

            line("--- verifying exported prefab ---");
            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(report.PrefabPath);
            if (prefab == null)
            {
                line("could not load the prefab back");
                return;
            }

            int renderers = 0, nullMesh = 0, nullMaterial = 0, shaderOk = 0, shaderBad = 0, boundTextures = 0;
            var shaders = new HashSet<string>();

            foreach (var renderer in prefab.GetComponentsInChildren<Renderer>(true))
            {
                renderers++;
                var skinned = renderer as SkinnedMeshRenderer;
                if (skinned != null && skinned.sharedMesh == null)
                    nullMesh++;

                foreach (var material in renderer.sharedMaterials)
                {
                    if (material == null)
                    {
                        nullMaterial++;
                        continue;
                    }

                    if (material.shader == null || material.shader.name.Contains("InternalError"))
                        shaderBad++;
                    else
                        shaderOk++;

                    if (material.shader != null)
                        shaders.Add(material.shader.name);

                    foreach (var property in material.GetTexturePropertyNames())
                    {
                        if (material.GetTexture(property) != null)
                            boundTextures++;
                    }
                }
            }

            line("renderers=" + renderers + " nullMesh=" + nullMesh + " nullMaterial=" + nullMaterial);
            line("shaderOK=" + shaderOk + " shaderBAD=" + shaderBad + " boundTextureSlots=" + boundTextures);
            line("shaders used after rebuild:");
            foreach (var name in shaders)
                line("   " + name);
        }
    }
}
#endif
