// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;

namespace EzAdmin.EditorTools
{
    [InitializeOnLoad]
    internal static class EzAdminMetaDefine
    {
        private const string Define = "EZADMIN_META_PLATFORM";

        static EzAdminMetaDefine()
        {
            EditorApplication.delayCall += Sync;
        }

        [MenuItem("Tools/EzAdmin/Check Meta Platform SDK")]
        private static void SyncFromMenu()
        {
            Sync();
            Debug.Log(Has() ? "EzAdmin: Meta hardware checks are on for Android builds."
                            : "EzAdmin: the Meta Platform SDK was not found, so Meta hardware checks are off.");
        }

        private static bool Has()
        {
            string current = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android) ?? "";
            return current.Split(';').Any(d => d.Trim() == Define);
        }

        private static void Sync()
        {
            if (EditorApplication.isCompiling || EditorApplication.isUpdating) return;
            bool reachable = MetaReachable();
            string current = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android) ?? "";
            var defines = current.Split(';').Select(d => d.Trim()).Where(d => d.Length > 0).ToList();
            bool has = defines.Contains(Define);
            if (reachable == has) return;
            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android && !reachable) return;
            if (reachable) defines.Add(Define);
            else defines.Remove(Define);
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, string.Join(";", defines));
            Debug.Log(reachable
                ? "EzAdmin: found the Meta Platform SDK. Meta hardware checks are now built into Android builds."
                : "EzAdmin: the Meta Platform SDK is gone, so Meta hardware checks were taken out of Android builds.");
        }

        private static bool MetaReachable()
        {
            foreach (var assembly in CompilationPipeline.GetAssemblies(AssembliesType.Player))
            {
                if (!assembly.sourceFiles.Any(f => f.EndsWith("EzAdminAttestation.cs"))) continue;
                return assembly.assemblyReferences.Any(r => r.name == "Oculus.Platform") ||
                       assembly.compiledAssemblyReferences.Any(r => Path.GetFileNameWithoutExtension(r) == "Oculus.Platform");
            }
            return false;
        }
    }
}
