using System.IO;
using UnityEditor;

namespace MajacloudSdk.Editor
{
    /// <summary>Resolves where the SDK lives (Assets/Majacloud or a package) and where generated assets go.</summary>
    internal static class MajacloudEditorPaths
    {
        public const string SettingsAssetPath = "Assets/Resources/MajacloudSettings.asset";
        public const string PackageVersion = Majacloud.Version;
        public const string DocsUrl = "https://github.com/majanite/majacloud";

        public static string SdkRoot
        {
            get
            {
                foreach (var guid in AssetDatabase.FindAssets("Majacloud.Editor t:AssemblyDefinitionAsset"))
                {
                    var path = AssetDatabase.GUIDToAssetPath(guid).Replace('\\', '/');
                    const string suffix = "/Editor/Majacloud.Editor.asmdef";
                    if (path.EndsWith(suffix)) return path.Substring(0, path.Length - suffix.Length);
                }
                return "Assets/Majacloud";
            }
        }

        public static bool IsPackage => SdkRoot.StartsWith("Packages/");

        public static string SamplesRoot => IsPackage ? "Assets/Samples/Majacloud/" + PackageVersion + "/Starter" : SdkRoot + "/Samples/Starter";
        public static string ScenesPath => SamplesRoot + "/Scenes";
        public static string PrefabsPath => SamplesRoot + "/Prefabs";
        public static string ArtPath => SamplesRoot + "/Art";
        public static string ScenePath(string fileName) => ScenesPath + "/" + fileName + ".unity";
        public static string HomeScenePath => ScenePath(DemoScenes.Home);
        /// <summary>The single scene shipped before 2.1; removed when the demo scenes are rebuilt.</summary>
        public static string LegacyStarterScenePath => ScenesPath + "/MajacloudStarter.unity";

        public static void EnsureFolder(string assetPath)
        {
            assetPath = assetPath.Replace('\\', '/').TrimEnd('/');
            if (AssetDatabase.IsValidFolder(assetPath)) return;
            var parent = Path.GetDirectoryName(assetPath)?.Replace('\\', '/');
            if (!string.IsNullOrEmpty(parent) && !AssetDatabase.IsValidFolder(parent)) EnsureFolder(parent);
            AssetDatabase.CreateFolder(parent, Path.GetFileName(assetPath));
        }
    }
}
