using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using VRC.SDK3.Avatars.Components;
using Object = UnityEngine.Object;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Quick menu export (uses the avatar's saved settings from the exporter window) and the batch-mode entry.
    ///
    /// Batch mode (used by AI/CI, D-015):
    ///   Unity.exe -batchmode -quit -projectPath "&lt;project&gt;" -logFile "&lt;log&gt;"
    ///     -executeMethod VCam.Exporter.Export.ExportMenu.Batch -vcamScene "Assets/x.unity" -vcamOutDir "&lt;dir&gt;"
    ///     [-vcamState scene|inGameDefault] [-vcamMaxTexture 2048] [-vcamCapture true|false] [-vcamReport true|false] [-vcamSuffix "_x"]
    /// Starts from each avatar's saved settings (&lt;project&gt;/UserSettings/VirtualCam/&lt;avatar&gt;.json) and lets the
    /// arguments override them. Writes &lt;dir&gt;/&lt;avatar&gt;&lt;suffix&gt;.vrm, and for checking (on unless turned off, since batch
    /// runs are for development) .vcam-report.json and .ref-*.png. The menus write the .vrm alone (D-092).
    /// </summary>
    internal static class ExportMenu
    {
        private const string MenuPath = "Tools/Virtual Cam Exporter/VRM 빠른 내보내기...";

        [MenuItem(MenuPath, false, 1)]
        private static void ExportSelected()
        {
            var avatar = SelectedAvatar();
            if (avatar == null) return;
            var options = ExportOptions.LoadFor(avatar.name);
            // Start in the avatar's saved folder and remember a new choice, like the exporter window (D-073).
            var folder = options.ResolvedOutputFolder();
            Directory.CreateDirectory(folder);
            var path = EditorUtility.SaveFilePanel("Virtual Cam용 VRM 내보내기", folder, ExportOptions.SafeFileName(avatar.name) + ".vrm", "vrm");
            if (string.IsNullOrEmpty(path)) return;
            var chosen = Path.GetDirectoryName(Path.GetFullPath(path));
            if (!string.Equals(chosen, Path.GetFullPath(folder), System.StringComparison.OrdinalIgnoreCase))
            {
                options.outputFolder = chosen;
                options.SaveFor(avatar.name);
            }
            var result = VCamExporter.Export(avatar, path, options);
            if (EditorUtility.DisplayDialog("Virtual Cam 내보내기", result.Summary, "폴더 열기", "닫기"))
                EditorUtility.RevealInFinder(result.Ok ? result.OutputPath : Path.GetDirectoryName(Path.GetFullPath(result.OutputPath)));
        }

        [MenuItem(MenuPath, true)]
        private static bool ValidateExportSelected() => SelectedAvatar() != null;

        private static GameObject SelectedAvatar()
        {
            var go = Selection.activeGameObject;
            var d = go != null ? go.GetComponentInParent<VRCAvatarDescriptor>(true) : null;
            return d != null ? d.gameObject : null;
        }

        public static void Batch()
        {
            var exitCode = 1;
            try
            {
                var scene = Arg("-vcamScene");
                if (!string.IsNullOrEmpty(scene)) EditorSceneManager.OpenScene(scene, OpenSceneMode.Single);
                var outDir = Arg("-vcamOutDir") ?? Path.Combine(Directory.GetParent(Application.dataPath).FullName, "VCamExport");
                var suffix = Arg("-vcamSuffix") ?? "";

                var avatars = Object.FindObjectsOfType<VRCAvatarDescriptor>(true)
                    .Select(d => d.gameObject)
                    .Where(go => go.transform.parent == null || go.transform.parent.GetComponentInParent<VRCAvatarDescriptor>(true) == null)
                    // Skip leftover bake/test copies saved in the scene (see AvatarBaker.IsBakedCopy).
                    .Where(go => !VCam.Exporter.Pipeline.AvatarBaker.IsBakedCopy(go))
                    .ToArray();
                Debug.Log($"[VCam] export: {avatars.Length} avatar(s) → {outDir}");

                var allOk = avatars.Length > 0;
                foreach (var avatar in avatars)
                {
                    var options = ExportOptions.LoadFor(avatar.name);
                    var state = Arg("-vcamState");
                    if (state != null) options.state = state.Equals("inGameDefault", StringComparison.OrdinalIgnoreCase) ? ExportState.InGameDefault : ExportState.Scene;
                    if (int.TryParse(Arg("-vcamMaxTexture"), out var maxTex)) options.maxTextureSize = maxTex;
                    options.captureReference = !bool.TryParse(Arg("-vcamCapture"), out var capture) || capture;
                    options.writeReport = !bool.TryParse(Arg("-vcamReport"), out var writeReport) || writeReport;

                    var safe = new string(avatar.name.Select(ch => Path.GetInvalidFileNameChars().Contains(ch) ? '_' : ch).ToArray());
                    var result = VCamExporter.Export(avatar, Path.Combine(outDir, safe + suffix + ".vrm"), options);
                    allOk &= result.Ok;
                    Debug.Log($"[VCam] EXPORT {(result.Ok ? "OK" : "FAIL")} {avatar.name} ({options.state}) -> {result.OutputPath}");
                }
                exitCode = allOk ? 0 : 1;
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Debug.Log($"[VCam] export batch finished, exit code {exitCode}");
                EditorApplication.Exit(exitCode);
            }
        }

        private static string Arg(string name)
        {
            var args = Environment.GetCommandLineArgs();
            var i = Array.IndexOf(args, name);
            // Unity drops empty arguments (""), so a value that is itself an option means "no value".
            if (i < 0 || i + 1 >= args.Length || args[i + 1].StartsWith("-vcam", StringComparison.Ordinal)) return null;
            return args[i + 1];
        }
    }
}
