using UnityEngine;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Registry system for looking up WeaponItem assets by name or weapon type
/// Used to convert string-based weapon references to actual WeaponItem objects
/// </summary>
[CreateAssetMenu(fileName = "WeaponRegistry", menuName = "RPG/Systems/Weapon Registry")]
public class WeaponRegistry : ScriptableObject
{
    [Header("Available Weapons")]
    [SerializeField] private List<WeaponItem> availableWeapons = new List<WeaponItem>();

    private static WeaponRegistry _instance;
    public static WeaponRegistry Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = Resources.Load<WeaponRegistry>("WeaponRegistry");
                if (_instance == null)
                {
                    Debug.LogWarning("WeaponRegistry not found in Resources folder. Creating default registry.");
                    _instance = CreateInstance<WeaponRegistry>();
                }
            }
            return _instance;
        }
    }

    /// <summary>
    /// Find a WeaponItem by exact name match
    /// </summary>
    public WeaponItem GetWeaponByName(string weaponName)
    {
        if (string.IsNullOrEmpty(weaponName)) return null;

        return availableWeapons.FirstOrDefault(w =>
            w != null && string.Equals(w.itemName, weaponName, System.StringComparison.OrdinalIgnoreCase));
    }

    /// <summary>
    /// Find a WeaponItem by weapon type (finds first match of that type)
    /// </summary>
    public WeaponItem GetWeaponByType(WeaponType weaponType)
    {
        return availableWeapons.FirstOrDefault(w => w != null && w.weaponType == weaponType);
    }

    /// <summary>
    /// Find a WeaponItem by weapon type string (e.g., "Sword", "Bow")
    /// </summary>
    public WeaponItem GetWeaponByTypeString(string weaponTypeString)
    {
        if (string.IsNullOrEmpty(weaponTypeString)) return null;

        // Try to parse as WeaponType enum
        if (System.Enum.TryParse<WeaponType>(weaponTypeString, true, out WeaponType weaponType))
        {
            return GetWeaponByType(weaponType);
        }

        return null;
    }

    /// <summary>
    /// Get all weapons of a specific type
    /// </summary>
    public List<WeaponItem> GetWeaponsByType(WeaponType weaponType)
    {
        return availableWeapons.Where(w => w != null && w.weaponType == weaponType).ToList();
    }

    /// <summary>
    /// Get a random weapon of the specified type
    /// </summary>
    public WeaponItem GetRandomWeaponByType(WeaponType weaponType)
    {
        var weaponsOfType = GetWeaponsByType(weaponType);
        if (weaponsOfType.Count == 0) return null;

        int randomIndex = Random.Range(0, weaponsOfType.Count);
        return weaponsOfType[randomIndex];
    }

    /// <summary>
    /// Get the default/basic weapon for a weapon type
    /// Prioritizes weapons with "Simple" or "Basic" in the name
    /// </summary>
    public WeaponItem GetDefaultWeaponByType(WeaponType weaponType)
    {
        var weaponsOfType = GetWeaponsByType(weaponType);
        if (weaponsOfType.Count == 0) return null;

        // Try to find a "simple" or "basic" weapon first
        var simpleWeapon = weaponsOfType.FirstOrDefault(w =>
            w.itemName.ToLower().Contains("simple") ||
            w.itemName.ToLower().Contains("basic"));

        return simpleWeapon ?? weaponsOfType[0]; // Return first if no simple weapon found
    }

    /// <summary>
    /// Register a weapon in the registry (for runtime additions)
    /// </summary>
    public void RegisterWeapon(WeaponItem weapon)
    {
        if (weapon != null && !availableWeapons.Contains(weapon))
        {
            availableWeapons.Add(weapon);
        }
    }

    /// <summary>
    /// Get all available weapons
    /// </summary>
    public List<WeaponItem> GetAllWeapons()
    {
        return availableWeapons.Where(w => w != null).ToList();
    }

    /// <summary>
    /// Debug method to list all available weapons
    /// </summary>
    [ContextMenu("Debug List All Weapons")]
    public void DebugListAllWeapons()
    {
        Debug.Log($"=== WeaponRegistry: {availableWeapons.Count} weapons ===");
        foreach (var weapon in availableWeapons)
        {
            if (weapon != null)
            {
                Debug.Log($"• {weapon.itemName} ({weapon.weaponType}) - Damage: {weapon.minDamage}-{weapon.maxDamage}");
            }
        }
    }

    /// <summary>
    /// Initialize the registry with common weapons if empty
    /// </summary>
    [ContextMenu("Initialize Default Weapons")]
    public void InitializeDefaults()
    {
        // This would be called to auto-populate with default weapons
        // In practice, you'd manually assign weapons in the inspector
        Debug.Log("WeaponRegistry: Use the inspector to assign available weapons");
    }
}
