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

public class RemoveMissingScripts
{
    [MenuItem("Tools/Remove Missing Scripts/From Selected Objects in Hierarchy")]
    private static void RemoveMissingScriptsFromSelection()
    {
        // 获取选中的对象
        GameObject[] selectedObjects = Selection.gameObjects;

        if (selectedObjects.Length == 0)
        {
            Debug.LogWarning("No objects selected in Hierarchy.");
            return;
        }

        int totalRemoved = 0;

        // 遍历所有选中的对象
        foreach (GameObject go in selectedObjects)
        {
            // 包括所有子对象
            int removed = RemoveMissingScriptsRecursively(go);
            totalRemoved += removed;

            Debug.Log($"Removed {removed} missing scripts from {go.name} and its children.");
        }

        Debug.Log($"Total removed missing scripts: {totalRemoved}");
    }

    [MenuItem("Tools/Remove Missing Scripts/From Prefabs in Selected Folder")]
    private static void RemoveMissingScriptsFromPrefabsInFolder()
    {
        // 获取选中的文件夹
        string[] selectedFolderGUIDs = Selection.assetGUIDs;

        if (selectedFolderGUIDs.Length == 0)
        {
            Debug.LogWarning("No folder selected in Project window.");
            return;
        }

        string folderPath = AssetDatabase.GUIDToAssetPath(selectedFolderGUIDs[0]);
        if (!AssetDatabase.IsValidFolder(folderPath))
        {
            Debug.LogWarning("Selected asset is not a folder.");
            return;
        }

        // 查找所有预制件
        string[] prefabPaths = Directory.GetFiles(folderPath, "*.prefab", SearchOption.AllDirectories);

        if (prefabPaths.Length == 0)
        {
            Debug.LogWarning("No prefabs found in selected folder.");
            return;
        }

        int totalRemoved = 0;
        int processedPrefabs = 0;

        // 处理每个预制件
        foreach (string path in prefabPaths)
        {
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (prefab != null)
            {
                // 创建预制件的实例
                GameObject instance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;

                // 移除缺失脚本
                int removed = RemoveMissingScriptsRecursively(instance);
                totalRemoved += removed;

                if (removed > 0)
                {
                    // 应用修改到预制件
                    PrefabUtility.SaveAsPrefabAsset(instance, path);
                    Debug.Log($"Removed {removed} missing scripts from prefab: {path}");
                }

                // 销毁实例
                Object.DestroyImmediate(instance);
                processedPrefabs++;
            }
        }

        Debug.Log($"Processed {processedPrefabs} prefabs. Total removed missing scripts: {totalRemoved}");
    }

    private static int RemoveMissingScriptsRecursively(GameObject gameObject)
    {
        int removedCount = 0;

        // 处理当前对象
        removedCount += GameObjectUtility.RemoveMonoBehavioursWithMissingScript(gameObject);

        // 递归处理所有子对象
        foreach (Transform child in gameObject.transform)
        {
            removedCount += RemoveMissingScriptsRecursively(child.gameObject);
        }

        return removedCount;
    }
}