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

namespace EventsAppQuest.Editor.WebGLBuild
{
    /// <summary>
    /// Entry point para exportar WebGL via Unity em batchmode (sem abrir o Editor).
    ///
    /// Uso (exemplo):
    /// -executeMethod EventsAppQuest.Editor.WebGLBuild.WebGLBuildEntry.BuildWebGL -outputPath "/abs/path/web-build"
    /// </summary>
    public static class WebGLBuildEntry
    {
        // Ordem importa: esta lista define a primeira cena carregada automaticamente pelo WebGL.
        private static readonly string[] ScenePaths =
        {
            // Cenário Web de staging/teste (instalação + dashboard CRM mock).
            "Assets/Web/Scenes/WebInstall.unity",
            "Assets/Web/Scenes/HotelCRM.unity",
            "Assets/Web/Scenes/WebDashboard.unity",

            // Camadas Quest (opcional para navegação interna a partir do Main).
            "Assets/Presentation/Scenes/Bootstrap.unity",
            "Assets/Presentation/Scenes/Main.unity",
            "Assets/Presentation/Scenes/QuestPresentation.unity"
        };

        public static void BuildWebGL()
        {
            var args = Environment.GetCommandLineArgs();
            var outputPath = GetArgValue(args, "-outputPath");
            if (string.IsNullOrEmpty(outputPath))
                outputPath = Path.Combine(Directory.GetCurrentDirectory(), "web-build");

            // Ajuste: Unity espera path de diretório para WebGL (gera index.html + Build/ + TemplateData/).
            Directory.CreateDirectory(outputPath);

            var scenes = new List<string>();
            foreach (var scenePath in ScenePaths)
            {
                if (File.Exists(scenePath))
                    scenes.Add(scenePath);
                else
                    Debug.LogWarning("[WebGLBuildEntry] Scene not found: " + scenePath);
            }

            if (scenes.Count == 0)
                throw new Exception("[WebGLBuildEntry] Nenhuma cena encontrada. Verifique paths em ScenePaths.");

            // Saída limpa opcional: mantemos por padrão apenas para evitar deletar sem intenção.
            // Se quiser limpar: adicione um flag -clean no wrapper e implemente aqui.

            var options = new BuildPlayerOptions
            {
                scenes = scenes.ToArray(),
                locationPathName = outputPath,
                target = BuildTarget.WebGL,
                options = BuildOptions.None
            };

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

            Debug.Log("[WebGLBuildEntry] Build WebGL concluída em: " + outputPath);
        }

        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;
        }
    }
}

