using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Davanci.Nexus.Editor
{
    // Generates AppleTangle.cs / GooglePlayTangle.cs via Unity IAP's ObfuscationGenerator
    // (same output as Services → In-App Purchasing → Receipt Validation Obfuscator).
    public static class NexusIapTangleSetup
    {
        const string GeneratorType = "UnityEditor.Purchasing.ObfuscationGenerator, UnityEditor.Purchasing";

        public static string GenerateApple()
        {
            if (!NexusIapInstaller.Installed)
                return "Unity IAP is not installed.";

            var method = FindMethod("ObfuscateAppleSecrets");
            if (method == null)
                return "Unity IAP ObfuscationGenerator not found — update com.unity.purchasing.";

            try
            {
                string err = method.Invoke(null, null) as string;
                AssetDatabase.Refresh();
                return string.IsNullOrEmpty(err) ? null : err.Trim();
            }
            catch (Exception e)
            {
                return e.InnerException?.Message ?? e.Message;
            }
        }

        public static string GenerateGoogle(string base64LicensingKey)
        {
            if (!NexusIapInstaller.Installed)
                return "Unity IAP is not installed.";
            if (string.IsNullOrWhiteSpace(base64LicensingKey))
                return "Google Play licensing key is empty.";

            var method = FindMethod("ObfuscateGoogleSecrets");
            if (method == null)
                return "Unity IAP ObfuscationGenerator not found — update com.unity.purchasing.";

            try
            {
                string err = method.Invoke(null, new object[] { base64LicensingKey.Trim() }) as string;
                AssetDatabase.Refresh();
                return string.IsNullOrEmpty(err) ? null : err.Trim();
            }
            catch (Exception e)
            {
                return e.InnerException?.Message ?? e.Message;
            }
        }

        public static void GenerateAll(NexusConfig cfg)
        {
            if (cfg == null || !cfg.enableIap || !NexusIapInstaller.Installed) return;

            string appleErr = GenerateApple();
            if (!string.IsNullOrEmpty(appleErr))
                Debug.LogWarning($"[Nexus] AppleTangle generation: {appleErr}");
            else
                Debug.Log("[Nexus] AppleTangle.cs generated.");

            if (!string.IsNullOrWhiteSpace(cfg.googlePlayLicensingKey))
            {
                string googleErr = GenerateGoogle(cfg.googlePlayLicensingKey);
                if (!string.IsNullOrEmpty(googleErr))
                    Debug.LogWarning($"[Nexus] GooglePlayTangle generation: {googleErr}");
                else
                    Debug.Log("[Nexus] GooglePlayTangle.cs generated.");
            }
        }

        static MethodInfo FindMethod(string name)
        {
            var type = Type.GetType(GeneratorType);
            return type?.GetMethod(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        }
    }
}
