using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace CatsUdonTools.Editor
{
    /// <summary>
    /// 入稿 Prefab から辿れる依存アセットを集める。モデルファイル（FBX 等）のインポート設定が割り当てている
    /// マテリアルは辿らない。エディタ時のみ動作し、プレイヤービルドには含まれない。
    /// </summary>
    internal static class SubmissionDependencyCollector
    {
        /// <summary>
        /// rootAssetPath 自身を含む依存アセットのパスを返す。
        /// Why: Renderer のマテリアルは入稿フォルダの複製に差し替え済みだが、FBX の .meta（externalObjects）は
        /// 元のマテリアルを指したままで、AssetDatabase.GetDependencies(path, true) ではそこから元のテクスチャまで
        /// 入稿物に入ってしまう。Prefab は複製側しか使わないため、モデルファイルのマテリアル割り当ては辿らない。
        /// </summary>
        public static string[] Collect(string rootAssetPath)
        {
            var collectedPaths = new HashSet<string> { rootAssetPath };
            var pendingPaths = new Queue<string>();
            pendingPaths.Enqueue(rootAssetPath);

            while (pendingPaths.Count > 0)
            {
                var currentPath = pendingPaths.Dequeue();
                var isModelFile = AssetImporter.GetAtPath(currentPath) is ModelImporter;
                foreach (var dependencyPath in AssetDatabase.GetDependencies(currentPath, false))
                {
                    if (isModelFile && IsMaterial(dependencyPath))
                    {
                        continue;
                    }

                    if (collectedPaths.Add(dependencyPath))
                    {
                        pendingPaths.Enqueue(dependencyPath);
                    }
                }
            }

            var result = new string[collectedPaths.Count];
            collectedPaths.CopyTo(result);
            return result;
        }

        private static bool IsMaterial(string assetPath)
        {
            return AssetDatabase.GetMainAssetTypeAtPath(assetPath) == typeof(Material);
        }
    }
}
