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

namespace VCam.Exporter.Spike
{
    /// <summary>
    /// Batch-mode entry point for the M0 bake test, so an AI (or CI) can run it without the Unity UI:
    ///
    ///   Unity.exe -batchmode -quit -projectPath "&lt;project&gt;" -logFile "&lt;log&gt;"
    ///     -executeMethod VCam.Exporter.Spike.BakeSpikeBatch.Run -vcamScene "Assets/xxx.unity"
    ///
    /// Opens the scene, runs the bake test on every avatar (VRCAvatarDescriptor) in it, writes one report per
    /// avatar to &lt;project&gt;/VCamExport/, and exits with 0 (all ok) or 1. The scene is never saved.
    /// Log lines are prefixed with "[VCam]" so they are easy to grep from the Unity log.
    /// </summary>
    internal static class BakeSpikeBatch
    {
        public static void Run()
        {
            var exitCode = 1;
            try
            {
                var scene = ArgValue("-vcamScene");
                if (!string.IsNullOrEmpty(scene))
                {
                    EditorSceneManager.OpenScene(scene, OpenSceneMode.Single);
                    Debug.Log($"[VCam] opened scene {scene}");
                }

                var avatars = Object.FindObjectsOfType<VRCAvatarDescriptor>(true)
                    .Select(d => d.gameObject)
                    // Skip nested descriptors (an avatar inside another avatar's hierarchy).
                    .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] found {avatars.Length} avatar(s): {string.Join(", ", avatars.Select(a => a.name))}");

                var allOk = avatars.Length > 0;
                foreach (var avatar in avatars)
                {
                    var outcome = BakeSpikeMenu.RunCore(avatar, keepClone: false);
                    allOk &= outcome.Ok;
                    Debug.Log($"[VCam] RESULT {(outcome.Ok ? "OK" : "FAIL")} {avatar.name} -> {outcome.ReportPath}");
                }
                exitCode = allOk ? 0 : 1;
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                Debug.Log($"[VCam] batch finished, exit code {exitCode}");
                EditorApplication.Exit(exitCode);
            }
        }

        private static string ArgValue(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];
        }
    }
}
