namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "natural_gift")]
public class NaturalGift : Script, IScriptChangeMoveType, IScriptOnSecondaryEffect, IScriptChangeBasePower
{
    /// <inheritdoc />
    public void ChangeBasePower(IExecutingMove move, IPokemon target, byte hit, ref ushort basePower)
    {
        var naturalGiftData = GetNaturalGiftData(move.User.HeldItem);
        if (naturalGiftData == null)
        {
            move.GetHitData(target, hit).Fail();
            return;
        }
        basePower = (byte)naturalGiftData.Value.power;
    }

    /// <inheritdoc />
    public void ChangeMoveType(IExecutingMove move, IPokemon target, byte hit, ref TypeIdentifier? moveType)
    {
        var naturalGiftData = GetNaturalGiftData(move.User.HeldItem);
        if (naturalGiftData == null)
        {
            move.GetHitData(target, hit).Fail();
            return;
        }
        var typeLibrary = move.User.Library.StaticLibrary.Types;
        if (!typeLibrary.TryGetTypeIdentifier(naturalGiftData.Value.type, out var type))
        {
            move.GetHitData(target, hit).Fail();
            return;
        }
        moveType = type;
    }

    /// <inheritdoc />
    public void OnSecondaryEffect(IExecutingMove move, IPokemon target, byte hit)
    {
        _ = move.User.RemoveHeldItem();
    }

    private static (int power, StringKey type)? GetNaturalGiftData(IItem? item)
    {
        if (item == null)
            return null;
        if (!item.AdditionalData.TryGetValue("naturalGift", out var data) ||
            data is not IReadOnlyDictionary<string, object> dict)
            return null;

        if (dict.TryGetValue("power", out var power) && dict.TryGetValue("type", out var type))
        {
            return ((int)power, (StringKey)(string)type);
        }
        return null;
    }
}