using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace EventsAppQuest.Editor.WindowsBuild
{
    /// <summary>
    /// Exporta build Windows (Standalone) para validação rápida do fluxo do Quest.
    ///
    /// Uso:
    /// -executeMethod EventsAppQuest.Editor.WindowsBuild.QuestWindowsBuildEntry.BuildQuestWindows
    /// -outputPath "/abs/path/windows-build"
    /// </summary>
    public static class QuestWindowsBuildEntry
    {
        private static readonly string[] ScenePaths =
        {
            "Assets/Presentation/Scenes/QuestPresentation.unity",
            // Mantém Main como fallback para voltar/completar navegação caso a build inclua UI de retorno.
            "Assets/Presentation/Scenes/Main.unity"
        };

        public static void BuildQuestWindows()
        {
            var projectRoot = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
            var args = Environment.GetCommandLineArgs();
            var outputPath = GetArgValue(args, "-outputPath");
            if (string.IsNullOrWhiteSpace(outputPath))
                outputPath = Path.Combine(projectRoot, "builds/windows/quest-test");

            Directory.CreateDirectory(outputPath);

            var scenes = ScenePaths
                .Where(p => File.Exists(Path.Combine(projectRoot, p)))
                .ToArray();
            if (scenes.Length == 0)
                throw new Exception("[QuestWindowsBuildEntry] Nenhuma cena válida encontrada em ScenePaths.");

            var outFile = Path.Combine(outputPath, "EventsAppQuest-Win64");

            var options = new BuildPlayerOptions
            {
                scenes = scenes,
                locationPathName = outFile,
                target = BuildTarget.StandaloneWindows64,
                options = BuildOptions.Development | BuildOptions.AllowDebugging
            };

            var report = BuildPipeline.BuildPlayer(options);
            if (report.summary.result != BuildResult.Succeeded)
                throw new Exception("[QuestWindowsBuildEntry] Build falhou: " + report.summary.result);

            Debug.Log("[QuestWindowsBuildEntry] Build Windows concluída em: " + outFile);
        }

        private static string GetArgValue(string[] args, string key)
        {
            if (args == null || args.Length == 0) return null;
            for (var i = 0; i < args.Length; i++)
            {
                if (!string.Equals(args[i], key, StringComparison.OrdinalIgnoreCase)) continue;
                if (i + 1 >= args.Length) return null;
                return args[i + 1];
            }
            return null;
        }
    }
}

