#region Header

// Copyright (c) 2025 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.

#endregion

using UnityEditor;
using UnityEngine;
using System.IO;

namespace BlackBox
{
    [InitializeOnLoad]
    public static class BlackBoxCertInstaller
    {
        private const string certPath = "../Certificates/Thirdparty/cacert.pem";
        private const string targetFolder = "Assets/StreamingAssets/cert/";
        private const string targetPath = targetFolder + "cacert.pem";

        static BlackBoxCertInstaller()
        {
            if (File.Exists(targetPath))
            {
                Debug.Log("[BlackBoxCertInstaller] PEM certificate already exists, skipping install.");
                return;
            }

            string sourceCertPath = GetFileRelativePath(certPath);
            if (!File.Exists(sourceCertPath))
            {
                Debug.LogWarning("[BlackBoxCertInstaller] cert file not found at " + sourceCertPath);
                return;
            }

            try
            {
                Directory.CreateDirectory(targetFolder);
                File.Copy(sourceCertPath, targetPath, overwrite: false);
                AssetDatabase.Refresh();

                Debug.Log($"[BlackBoxCertInstaller] PEM certificate installed to: {targetPath}");
            }
            catch (IOException ex)
            {
                Debug.LogError("[BlackBoxCertInstaller] Failed to copy PEM certificate: " + ex.Message);
            }
        }

        private static string GetFileRelativePath(string filePath)
        {
            // Try to find this script by name
            string[] guids = AssetDatabase.FindAssets("BlackboxCertInstaller t:Script");
            if (guids.Length == 0)
            {
                Debug.LogError("[BlackBoxCertInstaller] Could not find BlackboxCertInstaller script.");
                return null;
            }

            string scriptPath = AssetDatabase.GUIDToAssetPath(guids[0]);
            if (string.IsNullOrEmpty(scriptPath))
            {
                Debug.LogError("[BlackBoxCertInstaller] BlackboxCertInstaller script path is null or empty.");
                return null;
            }

            string editorFolder = Path.GetDirectoryName(scriptPath);
            string targetPath = Path.Combine(editorFolder, filePath);
            string fullPath = Path.GetFullPath(targetPath).Replace("\\", "/");

            return fullPath;
        }
    }
}