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

namespace EventsAppQuest.Editor.AndroidBuild
{
    /// <summary>
    /// Exporta APK Android/Quest em batchmode.
    ///
    /// Uso (exemplo):
    /// -executeMethod EventsAppQuest.Editor.AndroidBuild.QuestAndroidBuildEntry.BuildQuestApk
    /// -outputPath "/abs/path/quest-android-build"
    /// </summary>
    public static class QuestAndroidBuildEntry
    {
        private static readonly string[] ScenePaths =
        {
            "Assets/Presentation/Scenes/QuestPresentation.unity"
        };

        public static void BuildQuestApk()
        {
            // Project root: ../ from Assets/
            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/android");

            Directory.CreateDirectory(outputPath);

            try
            {
                // ARM64 (Quest)
                PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64;
            }
            catch
            {
                // ignora (caso API/versão do Unity não suporte)
            }

            try
            {
                // Força IL2CPP no Android (Quest).
                PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
            }
            catch
            {
                // ignora
            }

            try
            {
                // Package name consistente.
                PlayerSettings.applicationIdentifier = "com.eventsappquest.quest";
                PlayerSettings.companyName = "EventsAppQuest";
                PlayerSettings.productName = "EventsAppQuest Quest";
            }
            catch
            {
                // ignora
            }

            try
            {
                // Meta Quest usa API 29+; alvo moderno em builds atuais.
                PlayerSettings.Android.minSdkVersion = AndroidSdkVersions.AndroidApiLevel29;
                PlayerSettings.Android.targetSdkVersion = AndroidSdkVersions.AndroidApiLevel33;
            }
            catch
            {
                // ignora
            }

            try
            {
                // VR/Quest: landscape padrão.
                PlayerSettings.defaultInterfaceOrientation = UIOrientation.LandscapeLeft;
            }
            catch
            {
                // ignora
            }

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

            // BuildPlayerOptions.locationPathName para Android define o output.
            var outFile = Path.Combine(outputPath, "quest-debug.apk");

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

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

            Debug.Log("[QuestAndroidBuildEntry] Build Android/Quest 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;
        }
    }
}

