using UnityEditor;
using UnityEngine;

/// <summary>
/// Tools > Block World Setup — добавляет все нужные объекты в сцену.
/// </summary>
public static class BlockSetupTool
{
    [MenuItem("Tools/Block World Setup")]
    public static void Setup()
    {
        // ── BlockRegistry ────────────────────────────────────────────────────
        var registry = Object.FindObjectOfType<BlockRegistry>();
        if (registry == null)
        {
            var go = new GameObject("BlockRegistry");
            registry = go.AddComponent<BlockRegistry>();

            var shader = Shader.Find("Blocks/VoxelLit");
            if (shader != null) registry.voxelShader = shader;
            else Debug.LogWarning("[BlockSetup] Shader 'Blocks/VoxelLit' not found. Assign manually.");

            Debug.Log("[BlockSetup] Created BlockRegistry.");
        }

        // ── WorldManager ──────────────────────────────────────────────────────
        var wm = Object.FindObjectOfType<WorldManager>();
        if (wm == null)
        {
            var go = new GameObject("WorldManager");
            wm = go.AddComponent<WorldManager>();
            wm.registry = registry;
            Debug.Log("[BlockSetup] Created WorldManager.");
        }

        // ── FlatWorldGenerator ────────────────────────────────────────────────
        var gen = Object.FindObjectOfType<FlatWorldGenerator>();
        if (gen == null)
        {
            var go = new GameObject("FlatWorldGenerator");
            gen = go.AddComponent<FlatWorldGenerator>();
            Debug.Log("[BlockSetup] Created FlatWorldGenerator.");
        }

        // ── BlockPlacer на Player ─────────────────────────────────────────────
        var player = GameObject.FindWithTag("Player");
        if (player != null)
        {
            if (player.GetComponent<BlockPlacer>() == null)
            {
                var placer = player.AddComponent<BlockPlacer>();

                // Назначаем breakMaterial
                var breakShader = Shader.Find("Blocks/BlockBreak");
                if (breakShader != null)
                    placer.breakMaterial = new Material(breakShader);

                // Layer mask: ищем слой "BlockLayer", иначе напоминаем
                int layer = LayerMask.NameToLayer("BlockLayer");
                if (layer >= 0)
                    placer.blockLayer = 1 << layer;
                else
                    Debug.LogWarning("[BlockSetup] Layer 'BlockLayer' not found. Создай его и назначь чанкам, затем задай blockLayer в BlockPlacer.");

                Debug.Log("[BlockSetup] Added BlockPlacer to Player.");
            }
        }
        else
        {
            Debug.LogWarning("[BlockSetup] Player not found. Добавь BlockPlacer на объект с тегом 'Player' вручную.");
        }

        Selection.activeGameObject = wm.gameObject;

        EditorUtility.DisplayDialog(
            "Block World Setup",
            "Готово!\n\n" +
            "Что нужно сделать вручную:\n" +
            "1. BlockRegistry → добавь свои BlockDefinition в список\n" +
            "2. Создай слой 'BlockLayer' (Project Settings > Tags & Layers)\n" +
            "3. Назначь слой 'BlockLayer' чанкам (через chunkPrefab или скрипт)\n" +
            "4. BlockPlacer → назначь breakLayer и crackTexture\n" +
            "5. Запусти сцену — FlatWorldGenerator сгенерирует мир автоматически",
            "OK");
    }

    [MenuItem("Tools/Create Block Definition")]
    static void CreateBlockDefinition()
    {
        string folder = "Assets/Blocks/Definitions";
        if (!System.IO.Directory.Exists(folder))
            System.IO.Directory.CreateDirectory(folder);

        var def = ScriptableObject.CreateInstance<BlockDefinition>();
        def.blockId     = "new_block";
        def.displayName = "New Block";

        string path = AssetDatabase.GenerateUniqueAssetPath($"{folder}/NewBlock.asset");
        AssetDatabase.CreateAsset(def, path);
        AssetDatabase.SaveAssets();
        Selection.activeObject = def;
        Debug.Log($"[BlockSetup] Created BlockDefinition: {path}");
    }
}
