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

namespace WPFMA
{
    public sealed class WPFMAVrcaRipperWindow : EditorWindow
    {
        private const string WindowTitle = "WPFMA-SDK Exporter";
        private const string DefaultOutputName = "WPFMA_Rips";
        private const string DefaultProjectFolder = "Assets/WPFMA-SDK/Rips~";

        private const string OutputPrefKey = "WPFMA.VrcaRipper.OutputRoot";
        private const string ScenePrefKey = "WPFMA.VrcaRipper.UsePreviewScene";
        private const string GroundPrefKey = "WPFMA.VrcaRipper.IncludeGround";
        private const string CopyPrefKey = "WPFMA.VrcaRipper.CopyIntoProject";
        private const string ProjectFolderPrefKey = "WPFMA.VrcaRipper.ProjectFolder";
        private const string SettingsPrefKey = "WPFMA.VrcaRipper.SettingsExpanded";
        private const string ExportFolderPrefKey = "WPFMA.VrcaRipper.ExportFolder";
        private const string ExportShaderPrefKey = "WPFMA.VrcaRipper.ExportShader";
        private const string DefaultExportFolder = "Assets/WPFMA-SDK/Rips";

        private static Color PanelBackground => WPFMATheme.Shift(new Color(17f / 255f, 20f / 255f, 25f / 255f));
        private static Color DropBackground => WPFMATheme.Shift(new Color(33f / 255f, 38f / 255f, 46f / 255f));
        private static Color DropHighlight => WPFMATheme.Shift(new Color(40f / 255f, 66f / 255f, 88f / 255f));
        private static Color AccentBlue => WPFMATheme.Shift(new Color(126f / 255f, 182f / 255f, 222f / 255f));
        private static Color AccentText => WPFMATheme.Shift(new Color(14f / 255f, 24f / 255f, 33f / 255f));

        private sealed class Entry
        {
            public string Path;
            public string Header;
            public string Error;
            public bool Encrypted;
            public List<WPFMAVrcaNode> Nodes;
            public bool Expanded;
            public string Status;

            public bool Usable
            {
                get { return Error == null && !Encrypted; }
            }
        }

        private readonly List<Entry> entries = new List<Entry>();
        private string outputRoot;
        private string projectFolder;
        private bool usePreviewScene;
        private bool includeGround;
        private bool copyIntoProject;
        private bool settingsExpanded;
        private string exportFolder;
        private Shader exportShader;
        private Vector2 scrollPosition;
        private GUIStyle accentButtonStyle;

        private void OnEnable()
        {
            outputRoot = EditorPrefs.GetString(OutputPrefKey, string.Empty);
            if (string.IsNullOrEmpty(outputRoot))
                outputRoot = Path.Combine(ProjectRoot, DefaultOutputName);

            projectFolder = EditorPrefs.GetString(ProjectFolderPrefKey, DefaultProjectFolder);
            usePreviewScene = EditorPrefs.GetBool(ScenePrefKey, false);
            includeGround = EditorPrefs.GetBool(GroundPrefKey, true);
            copyIntoProject = EditorPrefs.GetBool(CopyPrefKey, false);
            settingsExpanded = EditorPrefs.GetBool(SettingsPrefKey, false);
            exportFolder = EditorPrefs.GetString(ExportFolderPrefKey, DefaultExportFolder);

            string shaderName = EditorPrefs.GetString(ExportShaderPrefKey, string.Empty);
            exportShader = string.IsNullOrEmpty(shaderName) ? null : Shader.Find(shaderName);
        }

        private static string ProjectRoot
        {
            get { return Directory.GetParent(Application.dataPath).FullName; }
        }

        public static void DrawEmbeddedInPanel(float panelWidth, float panelHeight)
        {
            var instance = new WPFMAVrcaRipperWindow();
            instance.position = new Rect(0f, 0f, panelWidth, panelHeight);
            instance.DrawEmbeddedContent();
        }

        internal void DrawEmbeddedContent()
        {
            EnsureVisualStyles();
            EditorGUI.DrawRect(new Rect(0f, 0f, position.width, position.height), PanelBackground);

            EditorGUILayout.Space(6f);
            EditorGUILayout.LabelField(WindowTitle, EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Unpack .vrca archives, or preview the avatar inside one.", EditorStyles.miniLabel);
            EditorGUILayout.Space(8f);

            DrawDropArea();
            DrawSourceButtons();
            EditorGUILayout.Space(8f);
            DrawSettings();
            EditorGUILayout.Space(8f);

            using (var scroll = new EditorGUILayout.ScrollViewScope(scrollPosition))
            {
                scrollPosition = scroll.scrollPosition;
                DrawEntries();
            }

            EditorGUILayout.Space(6f);
            DrawFooter();
        }

        private void OnGUI()
        {
            DrawEmbeddedContent();
        }

        private void DrawDropArea()
        {
            var rect = GUILayoutUtility.GetRect(0f, 58f, GUILayout.ExpandWidth(true));
            var evt = Event.current;
            bool canAcceptDrag = CanAcceptDrag();
            bool hovering = rect.Contains(evt.mousePosition) &&
                            (evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform);

            EditorGUI.DrawRect(rect, hovering ? DropHighlight : DropBackground);

            var label = new GUIStyle(EditorStyles.whiteLabel) { alignment = TextAnchor.MiddleCenter };
            GUI.Label(rect, "Drag .vrca files or a folder here", label);

            if (!rect.Contains(evt.mousePosition))
                return;

            if (evt.type == EventType.DragUpdated)
            {
                if (canAcceptDrag)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    evt.Use();
                    Repaint();
                }
            }
            else if (evt.type == EventType.DragPerform)
            {
                if (canAcceptDrag)
                {
                    DragAndDrop.AcceptDrag();
                    foreach (var path in DragAndDrop.paths)
                        AddPath(path);
                    foreach (var obj in DragAndDrop.objectReferences)
                    {
                        var assetPath = AssetDatabase.GetAssetPath(obj);
                        if (!string.IsNullOrEmpty(assetPath))
                            AddPath(assetPath);
                    }
                    evt.Use();
                    Repaint();
                }
            }
        }

        private static bool CanAcceptDrag()
        {
            foreach (var path in DragAndDrop.paths)
            {
                if (string.IsNullOrEmpty(path))
                    continue;

                if (Directory.Exists(path))
                    return true;

                if (WPFMABundleFiles.IsBundle(path))
                    return true;
            }

            foreach (var obj in DragAndDrop.objectReferences)
            {
                var assetPath = AssetDatabase.GetAssetPath(obj);
                if (!string.IsNullOrEmpty(assetPath) && WPFMABundleFiles.IsBundle(assetPath))
                    return true;
            }

            return false;
        }

        private void DrawSourceButtons()
        {
            EditorGUILayout.Space(6f);
            using (new EditorGUILayout.HorizontalScope())
            {
                if (DrawActionButton("Add .vrca file", 26f))
                {
                    string picked = EditorUtility.OpenFilePanel("Select a bundle (.vrca, .vrcw, .vrcb)", string.Empty,
                        WPFMABundleFiles.PickerFilter);
                    if (!string.IsNullOrEmpty(picked))
                        AddPath(picked);
                }

                if (DrawActionButton("Add folder", 26f))
                {
                    string picked = EditorUtility.OpenFolderPanel("Select a folder of .vrca bundles", string.Empty, string.Empty);
                    if (!string.IsNullOrEmpty(picked))
                        AddPath(picked);
                }

                if (entries.Count > 0 && DrawActionButton("Clear list", 26f, GUILayout.Width(90f)))
                    entries.Clear();
            }
        }

        private void DrawSettings()
        {
            bool expanded = EditorGUILayout.Foldout(settingsExpanded, "Settings", true);
            if (expanded != settingsExpanded)
            {
                settingsExpanded = expanded;
                EditorPrefs.SetBool(SettingsPrefKey, expanded);
            }

            if (!settingsExpanded)
                return;

            EditorGUI.indentLevel++;

            EditorGUILayout.LabelField("Extract to", EditorStyles.boldLabel);
            using (new EditorGUILayout.HorizontalScope())
            {
                string edited = EditorGUILayout.TextField(outputRoot);
                if (edited != outputRoot)
                {
                    outputRoot = edited;
                    EditorPrefs.SetString(OutputPrefKey, outputRoot);
                }

                if (DrawActionButton("Browse", 20f, GUILayout.Width(80f)))
                {
                    string picked = EditorUtility.OpenFolderPanel("Choose an output folder", outputRoot, string.Empty);
                    if (!string.IsNullOrEmpty(picked))
                    {
                        outputRoot = picked;
                        EditorPrefs.SetString(OutputPrefKey, outputRoot);
                        GUI.FocusControl(null);
                    }
                }
            }

            if (IsInsideAssets(outputRoot) && !IsHiddenFromImporter(outputRoot))
            {
                EditorGUILayout.HelpBox(
                    "That folder is inside Assets, so Unity will try to import every extracted file. On large bundles that can stall the editor.",
                    MessageType.Warning);
            }

            EditorGUILayout.Space(8f);
            EditorGUILayout.LabelField("Unity project handoff", EditorStyles.boldLabel);

            bool scene = EditorGUILayout.ToggleLeft("Build a preview scene before previewing", usePreviewScene);
            if (scene != usePreviewScene)
            {
                usePreviewScene = scene;
                EditorPrefs.SetBool(ScenePrefKey, scene);
            }

            using (new EditorGUI.DisabledScope(!usePreviewScene))
            {
                bool ground = EditorGUILayout.ToggleLeft("Include a ground block", includeGround);
                if (ground != includeGround)
                {
                    includeGround = ground;
                    EditorPrefs.SetBool(GroundPrefKey, ground);
                }
            }

            bool copy = EditorGUILayout.ToggleLeft("Copy extracted files into the project after extracting", copyIntoProject);
            if (copy != copyIntoProject)
            {
                copyIntoProject = copy;
                EditorPrefs.SetBool(CopyPrefKey, copy);
            }

            using (new EditorGUI.DisabledScope(!copyIntoProject))
            {
                string editedFolder = EditorGUILayout.TextField("Project folder", projectFolder);
                if (editedFolder != projectFolder)
                {
                    projectFolder = editedFolder;
                    EditorPrefs.SetString(ProjectFolderPrefKey, projectFolder);
                }
            }

            if (copyIntoProject)
            {
                EditorGUILayout.HelpBox(
                    IsHiddenFromImporter(projectFolder)
                        ? "The trailing ~ keeps this folder inside the project but hidden from Unity's importer, so the copied files travel with the project without being imported. Remove it and Unity will import every file."
                        : "Unity will import everything copied here. Ending the folder name with ~ keeps the files in the project but skips importing them.",
                    IsHiddenFromImporter(projectFolder) ? MessageType.Info : MessageType.Warning);
            }

            EditorGUILayout.Space(10f);
            EditorGUILayout.LabelField("Avatar identity", EditorStyles.boldLabel);

            string rename = EditorPrefs.GetString(WPFMAVrcaExporter.RenamePrefKey, string.Empty);
            string editedRename = EditorGUILayout.TextField("Rename to", rename);
            if (editedRename != rename)
                EditorPrefs.SetString(WPFMAVrcaExporter.RenamePrefKey, editedRename);

            EditorGUILayout.LabelField(
                string.IsNullOrEmpty(editedRename.Trim())
                    ? "Leave empty to keep the name from the bundle."
                    : "The root object and the prefab file will both be named '" + editedRename.Trim() + "'.",
                EditorStyles.miniLabel);

            bool clearBlueprint = EditorPrefs.GetBool(WPFMAVrcaExporter.ClearBlueprintPrefKey, true);
            bool editedClear = EditorGUILayout.ToggleLeft("Clear the blueprint ID", clearBlueprint);
            if (editedClear != clearBlueprint)
                EditorPrefs.SetBool(WPFMAVrcaExporter.ClearBlueprintPrefKey, editedClear);

            EditorGUILayout.HelpBox(
                editedClear
                    ? "The exported prefab carries no blueprint ID, so uploading creates a new avatar. This is what " +
                      "you want when recovering onto an account that does not own the original record."
                    : "The blueprint ID is kept, so uploading tries to update that existing avatar. That only works " +
                      "on the account which owns it.",
                MessageType.None);

            EditorGUILayout.Space(4f);
            if (DrawActionButton("Build preview scene now", 24f))
                WPFMAVrcaPreview.CreatePreviewScene(includeGround);

            EditorGUILayout.Space(10f);
            EditorGUILayout.LabelField("While exporting", EditorStyles.boldLabel);

            var expiry = WPFMAArchive.ExpiresAt;
            bool expired = expiry > DateTime.MinValue && expiry < DateTime.UtcNow;
            bool unlocked = WPFMAArchive.IsUnlocked && !expired;

            using (new EditorGUILayout.HorizontalScope())
            {
                var lockStyle = new GUIStyle(EditorStyles.miniLabel)
                {
                    fontStyle = FontStyle.Bold,
                    normal = { textColor = unlocked ? new Color(93f / 255f, 202f / 255f, 165f / 255f) : new Color(239f / 255f, 159f / 255f, 39f / 255f) }
                };

                EditorGUILayout.LabelField(
                    unlocked ? "Archive: unlocked" : expired ? "Archive: expired" : "Archive: locked", lockStyle,
                    GUILayout.Width(120f));

                if (!unlocked && GUILayout.Button("Redeem a code", EditorStyles.miniButton, GUILayout.Width(110f)))
                    WPFMAWindow.OpenAtSettings();
            }

            using (new EditorGUI.DisabledScope(!unlocked))
            {
                bool fetchShaders = unlocked && EditorPrefs.GetBool(WPFMAVrcaExporter.FetchShadersPrefKey, true);
                bool editedFetch = EditorGUILayout.ToggleLeft("Download missing shaders from the archive", fetchShaders);
                if (unlocked && editedFetch != fetchShaders)
                    EditorPrefs.SetBool(WPFMAVrcaExporter.FetchShadersPrefKey, editedFetch);
            }

            EditorGUILayout.LabelField(
                unlocked
                    ? (string.IsNullOrEmpty(WPFMAArchive.Label)
                        ? "Off skips the lookup and matches against what is already installed."
                        : WPFMAArchive.Label + ". Off skips the lookup and matches what is installed.")
                    : expired
                        ? "That access code expired. Redeem a new one to pull missing shaders."
                        : "Redeem an access code to pull missing shaders while exporting.",
                EditorStyles.miniLabel);

            bool writeReport = EditorPrefs.GetBool(WPFMAVrcaExporter.WriteReportPrefKey, true);
            bool editedReport = EditorGUILayout.ToggleLeft("Write an export report", writeReport);
            if (editedReport != writeReport)
                EditorPrefs.SetBool(WPFMAVrcaExporter.WriteReportPrefKey, editedReport);

            EditorGUILayout.LabelField(
                "Saves 'export report.txt' beside the export: what came out, and what could not be recovered.",
                EditorStyles.miniLabel);

            bool verbose = EditorPrefs.GetBool(WPFMAVrcaExporter.VerboseLogPrefKey, true);
            bool editedVerbose = EditorGUILayout.ToggleLeft("Log each step to the console", verbose);
            if (editedVerbose != verbose)
                EditorPrefs.SetBool(WPFMAVrcaExporter.VerboseLogPrefKey, editedVerbose);

            EditorGUILayout.LabelField(
                "Off leaves only the start and finish lines, plus any warnings.",
                EditorStyles.miniLabel);

            EditorGUILayout.Space(10f);
            EditorGUILayout.LabelField("Export to project assets", EditorStyles.boldLabel);

            string editedExport = EditorGUILayout.TextField("Export folder", exportFolder);
            if (editedExport != exportFolder)
            {
                exportFolder = editedExport;
                EditorPrefs.SetString(ExportFolderPrefKey, exportFolder);
            }

            var editedShader = (Shader)EditorGUILayout.ObjectField("Target shader", exportShader, typeof(Shader), false);
            if (editedShader != exportShader)
            {
                exportShader = editedShader;
                EditorPrefs.SetString(ExportShaderPrefKey, exportShader != null ? exportShader.name : string.Empty);
            }

            EditorGUILayout.HelpBox(
                (exportShader == null
                    ? "Leave the shader empty and each material is matched to the installed shader sharing the most property names. "
                    : "Every material will be rebuilt on '" + exportShader.name + "'. ") +
                "Shaders themselves cannot be recovered — a bundle stores compiled GPU programs and a project shader is source, " +
                "so materials are rebuilt on a real shader and the recovered textures rebound by name.",
                MessageType.Info);

            EditorGUI.indentLevel--;
        }

        private void DrawEntries()
        {
            if (entries.Count == 0)
            {
                EditorGUILayout.HelpBox("No bundles queued.", MessageType.None);
                return;
            }

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

                using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
                {
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        entry.Expanded = EditorGUILayout.Foldout(entry.Expanded, Path.GetFileName(entry.Path), true);

                        using (new EditorGUI.DisabledScope(!entry.Usable))
                        {
                            if (DrawActionButton("Preview", 20f, GUILayout.Width(70f)))
                                PreviewEntry(entry);

                            if (DrawActionButton("Extract", 20f, GUILayout.Width(70f)))
                                ExtractEntries(new List<Entry> { entry });

                            if (DrawActionButton("Export", 20f, GUILayout.Width(70f)))
                                ExportEntry(entry);

                            if (DrawActionButton("Report", 20f, GUILayout.Width(70f)))
                                ReportEntry(entry);
                        }

                        if (GUILayout.Button("x", GUILayout.Width(22f)))
                        {
                            entries.RemoveAt(i);
                            i--;
                            continue;
                        }
                    }

                    if (entry.Error != null)
                        EditorGUILayout.HelpBox(entry.Error, MessageType.Error);
                    else if (entry.Encrypted)
                        EditorGUILayout.HelpBox(entry.Header + "\n\nThis bundle is encrypted, so its contents cannot be read.", MessageType.Warning);
                    else
                        EditorGUILayout.LabelField(entry.Header, EditorStyles.miniLabel);

                    if (entry.Expanded && entry.Nodes != null)
                    {
                        EditorGUI.indentLevel++;
                        foreach (var node in entry.Nodes)
                            EditorGUILayout.LabelField(node.Path, FormatSize(node.Size), EditorStyles.miniLabel);
                        EditorGUI.indentLevel--;
                    }

                    if (!string.IsNullOrEmpty(entry.Status))
                        EditorGUILayout.LabelField(entry.Status, EditorStyles.miniLabel);
                }
            }
        }

        private void DrawFooter()
        {
            var ready = new List<Entry>();
            foreach (var entry in entries)
            {
                if (entry.Usable)
                    ready.Add(entry);
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Extracts to  " + outputRoot, EditorStyles.miniLabel);
                if (DrawActionButton("Show", 18f, GUILayout.Width(60f)))
                    RevealOutputRoot();
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                using (new EditorGUI.DisabledScope(ready.Count == 0))
                {
                    if (DrawActionButton(ready.Count == 1 ? "Extract 1 bundle" : "Extract " + ready.Count + " bundles", 32f))
                        ExtractEntries(ready);
                }

                if (WPFMAVrcaPreview.HasPreview && DrawActionButton("Export preview", 32f, GUILayout.Width(130f)))
                    ExportPreview();

                if (WPFMAVrcaPreview.HasPreview && DrawActionButton("Clear preview", 32f, GUILayout.Width(120f)))
                    WPFMAVrcaPreview.Clear();
            }
        }

        private void RevealOutputRoot()
        {
            if (string.IsNullOrEmpty(outputRoot))
                return;

            Directory.CreateDirectory(outputRoot);
            EditorUtility.RevealInFinder(outputRoot);
        }

        private void PreviewEntry(Entry entry)
        {
            if (!WPFMAVrcaPreview.EnsureBuildTarget())
                return;

            if (usePreviewScene && !WPFMAVrcaPreview.HasPreview)
                WPFMAVrcaPreview.CreatePreviewScene(includeGround);

            string message;
            try
            {
                EditorUtility.DisplayProgressBar(WindowTitle, "Loading " + Path.GetFileName(entry.Path) + "…", 0.5f);
                var instance = WPFMAVrcaPreview.Preview(entry.Path, out message);
                entry.Status = instance != null ? "Preview: " + message : "Preview failed: " + message;

                if (instance == null)
                    Debug.LogWarning("[WPFMA-SDK] Could not preview " + entry.Path + ": " + message);
            }
            catch (Exception e)
            {
                entry.Status = "Preview failed: " + e.Message;
                Debug.LogError("[WPFMA-SDK] Could not preview " + entry.Path + ": " + e);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                Repaint();
            }
        }

        private bool ConfirmExportFolder(string projectRelativeFolder)
        {
            string full = Path.Combine(ProjectRoot, projectRelativeFolder);
            if (!Directory.Exists(full) || Directory.GetFileSystemEntries(full).Length == 0)
                return true;

            bool replace = EditorUtility.DisplayDialog(WindowTitle,
                projectRelativeFolder + " already contains an export.\n\n" +
                "Exporting again would add a second copy of every asset alongside the old one, and it is easy to end up " +
                "inspecting the stale prefab.\n\nReplace the existing export? The old one goes to the Recycle Bin.",
                "Replace", "Cancel");

            if (!replace)
                return false;

            if (!AssetDatabase.MoveAssetToTrash(projectRelativeFolder))
                AssetDatabase.DeleteAsset(projectRelativeFolder);
            AssetDatabase.Refresh();
            return true;
        }

        private void ReportEntry(Entry entry)
        {
            string destination = Path.Combine(
                Path.Combine(string.IsNullOrEmpty(outputRoot) ? ProjectRoot : outputRoot,
                    Path.GetFileNameWithoutExtension(entry.Path)),
                "export report.txt");

            try
            {
                string written = WPFMARipReport.Generate(entry.Path, destination, (fraction, status) =>
                        !EditorUtility.DisplayCancelableProgressBar(WindowTitle,
                            Path.GetFileName(entry.Path) + "  —  " + status, fraction),
                    WPFMAVrcaPreview.GetLoadedBundle(entry.Path));

                entry.Status = "Report written to " + written;
                Debug.Log("[WPFMA-SDK] Export report: " + written);
                EditorUtility.RevealInFinder(written);
            }
            catch (OperationCanceledException)
            {
                entry.Status = "Report cancelled.";
            }
            catch (Exception e)
            {
                entry.Status = "Report failed: " + e.Message;
                Debug.LogError("[WPFMA-SDK] Could not write a report for " + entry.Path + ": " + e);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                Repaint();
            }
        }

        private void WriteReportInto(string vrcaPath, string folderFullPath)
        {
            if (string.IsNullOrEmpty(vrcaPath) || !File.Exists(vrcaPath))
                return;

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

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

        private void ExportEntry(Entry entry)
        {
            if (!WPFMAVrcaPreview.EnsureBuildTarget())
                return;

            string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                            "/" + WPFMAVrcaExporter.RipFolderName(entry.Path);

            if (!ConfirmExportFolder(folder))
                return;

            try
            {
                var report = WPFMAVrcaExporter.Export(entry.Path, folder, exportShader, (fraction, status) =>
                    !EditorUtility.DisplayCancelableProgressBar(WindowTitle, Path.GetFileName(entry.Path) + "  —  " + status, fraction));

                entry.Status = "Exported " + report.Summary + " to " + folder;
                LogReport(Path.GetFileName(entry.Path), report);
                WriteReportInto(entry.Path, Path.Combine(ProjectRoot, folder));

                if (!string.IsNullOrEmpty(report.PrefabPath))
                {
                    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(report.PrefabPath);
                    if (prefab != null)
                    {
                        Selection.activeObject = prefab;
                        EditorGUIUtility.PingObject(prefab);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                entry.Status = "Export cancelled.";
            }
            catch (Exception e)
            {
                entry.Status = "Export failed: " + e.Message;
                Debug.LogError("[WPFMA-SDK] Could not export " + entry.Path + ": " + e);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                Repaint();
            }
        }

        private void ExportPreview()
        {
            var avatar = WPFMAVrcaPreview.GetPreviewedAvatar();
            if (avatar == null)
            {
                EditorUtility.DisplayDialog(WindowTitle, "Preview an avatar first, then export it.", "OK");
                return;
            }

            string intactReason;
            if (!WPFMAVrcaExporter.IsPreviewIntact(avatar, out intactReason))
            {
                EditorUtility.DisplayDialog(WindowTitle, intactReason, "OK");
                return;
            }

            string folder = (string.IsNullOrEmpty(exportFolder) ? DefaultExportFolder : exportFolder).TrimEnd('/', '\\') +
                            "/" + avatar.name;

            if (!ConfirmExportFolder(folder))
                return;

            try
            {
                var report = WPFMAVrcaExporter.ExportFromInstance(avatar, folder, exportShader, (fraction, status) =>
                    !EditorUtility.DisplayCancelableProgressBar(WindowTitle, avatar.name + "  —  " + status, fraction),
                    WPFMAVrcaPreview.GetFirstLoadedPath());

                LogReport(avatar.name + " (from preview)", report);
                WriteReportInto(WPFMAVrcaPreview.GetFirstLoadedPath(), Path.Combine(ProjectRoot, folder));

                if (!string.IsNullOrEmpty(report.PrefabPath))
                {
                    var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(report.PrefabPath);
                    if (prefab != null)
                    {
                        Selection.activeObject = prefab;
                        EditorGUIUtility.PingObject(prefab);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                Debug.LogWarning("[WPFMA-SDK] Preview export cancelled.");
            }
            catch (Exception e)
            {
                Debug.LogError("[WPFMA-SDK] Could not export the preview: " + e);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                Repaint();
            }
        }

        private static void LogReport(string label, WPFMAVrcaExporter.Report report)
        {
            var vrchat = report.VrchatComponents.OrderByDescending(c => c.Value).ToList();

            string components = vrchat.Count > 0
                ? "\nVRChat components kept: " + string.Join(", ", vrchat.Select(c => c.Key + " x" + c.Value))
                : "\nNo VRChat components resolved — check that the VRChat SDK is installed.";

            Debug.Log("[WPFMA-SDK] Exported " + label + ": " + report.Summary + components +
                      (report.MissingScriptsStripped > 0
                          ? "\nDropped " + report.MissingScriptsStripped + " component(s) with unresolvable scripts."
                          : string.Empty));

            foreach (var warning in report.Warnings)
                Debug.LogWarning("[WPFMA-SDK] " + warning);
        }

        private void ExtractEntries(List<Entry> targets)
        {
            if (string.IsNullOrEmpty(outputRoot))
            {
                EditorUtility.DisplayDialog(WindowTitle, "Choose an output folder first.", "OK");
                return;
            }

            EditorPrefs.SetString(OutputPrefKey, outputRoot);

            int succeeded = 0;
            int failed = 0;
            bool copied = false;

            try
            {
                foreach (var entry in targets)
                {
                    if (!entry.Usable)
                        continue;

                    string name = Path.GetFileNameWithoutExtension(entry.Path);
                    string destination = Path.Combine(outputRoot, name);

                    try
                    {
                        using (var stream = File.OpenRead(entry.Path))
                        {
                            var bundle = WPFMAVrcaBundle.Open(stream);
                            var written = bundle.Extract(stream, destination, (fraction, status) =>
                                !EditorUtility.DisplayCancelableProgressBar(WindowTitle, name + "  —  " + status, fraction));

                            entry.Status = "Extracted " + written.Count + " file(s) to " + destination;
                            succeeded++;
                        }

                        WriteReportInto(entry.Path, destination);

                        {
                        }

                        if (copyIntoProject)
                        {
                            string target = CopyIntoProject(destination, name);
                            entry.Status += "  |  copied to " + target;
                            copied = true;
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        entry.Status = "Cancelled.";
                        Debug.LogWarning("[WPFMA-SDK] VRCA extraction cancelled: " + entry.Path);
                        return;
                    }
                    catch (Exception e)
                    {
                        entry.Status = "Failed: " + e.Message;
                        failed++;
                        Debug.LogError("[WPFMA-SDK] Could not extract " + entry.Path + ": " + e);
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                Repaint();
            }

            if (copied && !IsHiddenFromImporter(projectFolder))
                AssetDatabase.Refresh();

            Debug.Log("[WPFMA-SDK] Exporter finished: " + succeeded + " extracted, " + failed + " failed.");
        }

        private string CopyIntoProject(string sourceDirectory, string name)
        {
            string relative = string.IsNullOrEmpty(projectFolder) ? DefaultProjectFolder : projectFolder;
            string destination = Path.Combine(Path.Combine(ProjectRoot, relative), name);

            Directory.CreateDirectory(destination);

            foreach (var file in Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories))
            {
                string tail = file.Substring(sourceDirectory.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                string copy = Path.Combine(destination, tail);
                Directory.CreateDirectory(Path.GetDirectoryName(copy));
                File.Copy(file, copy, true);
            }

            return relative + "/" + name;
        }

        private void AddPath(string path)
        {
            if (string.IsNullOrEmpty(path))
                return;

            if (Directory.Exists(path))
            {
                foreach (var file in WPFMABundleFiles.Find(path, SearchOption.AllDirectories))
                    AddFile(file);
                return;
            }

            if (File.Exists(path))
                AddFile(path);
        }

        private void AddFile(string path)
        {
            string full = Path.GetFullPath(path);
            foreach (var existing in entries)
            {
                if (string.Equals(existing.Path, full, StringComparison.OrdinalIgnoreCase))
                    return;
            }

            entries.Add(Inspect(full));
        }

        private static Entry Inspect(string path)
        {
            var entry = new Entry { Path = path };

            try
            {
                using (var stream = File.OpenRead(path))
                {
                    var bundle = WPFMAVrcaBundle.Open(stream);
                    entry.Encrypted = bundle.UsesContentEncryption;
                    entry.Nodes = bundle.Nodes;

                    entry.Header = entry.Encrypted
                        ? "UnityFS v" + bundle.FormatVersion + "  |  Unity " + bundle.UnityRevision + "  |  encrypted"
                        : "UnityFS v" + bundle.FormatVersion + "  |  Unity " + bundle.UnityRevision +
                          "  |  " + bundle.Blocks.Count + " blocks, " + bundle.Nodes.Count + " files" +
                          "  |  " + FormatSize(bundle.TotalUncompressedSize) + " unpacked";
                }
            }
            catch (Exception e)
            {
                entry.Error = e.Message;
            }

            return entry;
        }

        private static bool IsHiddenFromImporter(string path)
        {
            if (string.IsNullOrEmpty(path))
                return false;

            foreach (var segment in path.Split('/', '\\'))
            {
                if (segment.EndsWith("~", StringComparison.Ordinal) || segment.StartsWith(".", StringComparison.Ordinal))
                    return true;
            }

            return false;
        }

        private static bool IsInsideAssets(string path)
        {
            if (string.IsNullOrEmpty(path))
                return false;

            try
            {
                string assets = Path.GetFullPath(Application.dataPath);
                string candidate = Path.GetFullPath(path);
                return candidate.StartsWith(assets, StringComparison.OrdinalIgnoreCase);
            }
            catch (Exception)
            {
                return false;
            }
        }

        private static string FormatSize(long bytes)
        {
            if (bytes < 1024L)
                return bytes + " B";
            if (bytes < 1024L * 1024L)
                return (bytes / 1024f).ToString("F1") + " KB";
            if (bytes < 1024L * 1024L * 1024L)
                return (bytes / (1024f * 1024f)).ToString("F1") + " MB";
            return (bytes / (1024f * 1024f * 1024f)).ToString("F2") + " GB";
        }

        private void EnsureVisualStyles()
        {
            if (accentButtonStyle != null && accentButtonStyle.normal.background != null)
                return;

            var texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, AccentBlue);
            texture.Apply();
            texture.hideFlags = HideFlags.HideAndDontSave;

            accentButtonStyle = new GUIStyle(GUI.skin.button)
            {
                normal = { background = texture, textColor = AccentText },
                hover = { background = texture, textColor = AccentText },
                active = { background = texture, textColor = AccentText },
                focused = { background = texture, textColor = AccentText }
            };
        }

        private bool DrawActionButton(string label, float height, params GUILayoutOption[] options)
        {
            var layoutOptions = new GUILayoutOption[options.Length + 1];
            layoutOptions[0] = GUILayout.Height(height);
            options.CopyTo(layoutOptions, 1);
            return GUILayout.Button(label, accentButtonStyle, layoutOptions);
        }
    }
}
#endif
