namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "hidden_power")]
public class HiddenPower : Script, IScriptChangeMoveType, IScriptChangeBasePower
{
    /// <inheritdoc />
    public void ChangeMoveType(IExecutingMove move, IPokemon target, byte hit, ref TypeIdentifier? moveType)
    {
        var ivs = move.User.IndividualValues;

        var type = GetHiddenPowerValue(ivs, 0x00000001) * 15 / 63;

        if (move.User.Library.StaticLibrary.Types.TryGetTypeIdentifierFromIndex((byte)(type + 2), out var t))
            moveType = t;
    }

    /// <inheritdoc />
    public void ChangeBasePower(IExecutingMove move, IPokemon target, byte hit, ref ushort basePower)
    {
        var ivs = move.User.IndividualValues;

        var power = GetHiddenPowerValue(ivs, 0x00000002) * 40 / 63 + 30;
        // cast to byte with overflow check
        basePower = (byte)Math.Min(power, byte.MaxValue);
    }

    /// <summary>
    /// Helper method to calculate the hidden power value from the IVs.
    /// This is used to determine the type and power of the move.
    /// </summary>
    private static int GetHiddenPowerValue(IndividualValueStatisticSet ivs, int significance) =>
        ((ivs.Hp & significance) >> (significance - 1)) + (((ivs.Attack & significance) >> (significance - 1)) << 1) +
        (((ivs.Defense & significance) >> (significance - 1)) << 2) +
        (((ivs.Speed & significance) >> (significance - 1)) << 3) +
        (((ivs.SpecialAttack & significance) >> (significance - 1)) << 4) +
        (((ivs.SpecialDefense & significance) >> (significance - 1)) << 5);
}