using UnityEngine;
using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// Компонент для генерации ItemData ScriptableObject из настроек в Inspector.
/// Добавьте на GameObject, заполните поля и нажмите "Generate ItemData" в Inspector.
/// </summary>
public class ItemGenerator : MonoBehaviour
{
    [Header("Item Template")]
    public string itemId = "";
    public string itemName = "";
    public string description = "";
    public ItemType itemType = ItemType.Material;
    public Sprite icon;
    public GameObject modelPrefab;
    public int maxStack = 64;
    public bool isCraftable;

    [Header("Crafting (if craftable)")]
    public string[] craftIngredients;
    public int[] craftAmounts;
    public string craftResultId;
    public int craftResultAmount = 1;

    public ItemData GenerateItemData()
    {
        if (string.IsNullOrEmpty(itemId))
            itemId = System.Guid.NewGuid().ToString();

        var itemData = ScriptableObject.CreateInstance<ItemData>();
        itemData.id          = itemId;
        itemData.itemName    = itemName;
        itemData.description = description;
        itemData.type        = itemType;
        itemData.modelPrefab = modelPrefab;
        itemData.icon        = icon;
        itemData.maxStack    = maxStack;
        itemData.isCraftable = isCraftable;

        if (isCraftable && craftIngredients != null && craftIngredients.Length > 0)
        {
            itemData.craftingRecipe = new ItemData.CraftingRecipe
            {
                ingredients  = craftIngredients,
                amounts      = craftAmounts,
                resultId     = craftResultId,
                resultAmount = craftResultAmount
            };
        }

        return itemData;
    }

    public static List<ItemData> GenerateAll(List<ItemGenerator> generators)
    {
        var items = new List<ItemData>();
        foreach (var gen in generators)
        {
            if (gen != null)
                items.Add(gen.GenerateItemData());
        }
        return items;
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(ItemGenerator))]
public class ItemGeneratorEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        GUILayout.Space(8);

        if (GUILayout.Button("Generate ItemData"))
        {
            var generator = (ItemGenerator)target;
            var itemData  = generator.GenerateItemData();

            string folder = "Assets/Inventory/Items";
            if (!System.IO.Directory.Exists(folder))
                System.IO.Directory.CreateDirectory(folder);

            string path = $"{folder}/{itemData.itemName}.asset";
            AssetDatabase.CreateAsset(itemData, path);
            AssetDatabase.SaveAssets();

            Debug.Log($"[ItemGenerator] Created item: {itemData.itemName} at {path}");
        }
    }
}
#endif
