using System.Collections.Concurrent;
using System.Reflection;
using PkmnLib.Static.Utils;

namespace PkmnLib.Dynamic.ScriptHandling.Registry;

/// <summary>
/// Extension methods for scripts.
/// </summary>
public static class ScriptUtils
{
    private static readonly ConcurrentDictionary<Type, (ScriptCategory category, StringKey name)> Cache = new();

    /// <summary>
    /// Resolve name from the <see cref="ScriptAttribute"/> of the given script.
    /// </summary>
    public static StringKey ResolveName(this Script script) => ResolveName(script.GetType());

    /// <summary>
    /// Resolve name from the <see cref="ScriptAttribute"/> of the given type.
    /// </summary>
    public static StringKey ResolveName<T>() where T : Script => ResolveName(typeof(T));

    /// <summary>
    /// Resolve name from the <see cref="ScriptAttribute"/> of the given type.
    /// </summary>
    public static StringKey ResolveName(Type type) => GetFromCacheOrAdd(type).name;

    /// <summary>
    /// Resolve category from the <see cref="ScriptAttribute"/> of the given script.
    /// </summary>
    public static ScriptCategory ResolveCategory(this Script script) => ResolveCategory(script.GetType());

    /// <summary>
    /// Resolve category from the <see cref="ScriptAttribute"/> of the given script.
    /// </summary>
    public static ScriptCategory ResolveCategory<T>() where T : Script => ResolveCategory(typeof(T));

    /// <summary>
    /// Resolve category from the <see cref="ScriptAttribute"/> of the given type.
    /// </summary>
    public static ScriptCategory ResolveCategory(Type type) => GetFromCacheOrAdd(type).category;

    private static (ScriptCategory category, StringKey name) GetFromCacheOrAdd(Type type)
    {
        if (Cache.TryGetValue(type, out var key))
            return key;

        var scriptAttr = type.GetCustomAttribute<ScriptAttribute>();
        if (scriptAttr == null)
            throw new InvalidOperationException($"Type {type} does not have a {nameof(ScriptAttribute)}.");
        return Cache[type] = (scriptAttr.Category, scriptAttr.Name);
    }
}