namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Anticipation is an ability that alerts the user if any opponent has a super effective, OHKO, or self-destruct move upon entering battle.
/// The alert is triggered if an opponent knows a move that is super effective against the user, or a move with the OHKO or self-destruct effect.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Anticipation_(Ability)">Bulbapedia - Anticipation</see>
/// </summary>
[Script(ScriptCategory.Ability, "anticipation")]
public class Anticipation : Script, IScriptOnOpponentSwitchIn
{
    private IPokemon? _owner;

    /// <inheritdoc />
    public override void OnAddedToParent(IScriptSource source)
    {
        if (source is not IPokemon pokemon)
            throw new ArgumentException("Anticipation script can only be added to a Pokemon.", nameof(source));
        _owner = pokemon;
    }

    /// <inheritdoc />
    public void OnOpponentSwitchIn(IPokemon pokemon, byte position)
    {
        if (_owner is null)
            return;
        var pokemonMoves = pokemon.Moves.WhereNotNull();
        var typeLibrary = pokemon.Library.StaticLibrary.Types;
        var relevantMoves = pokemonMoves.Any(move =>
            // Either the move is super effective against the owner or
            typeLibrary.GetEffectiveness(move.MoveData.MoveType, _owner.Types) > 1.0f ||
            // the move is a OHKO move
            move.MoveData.SecondaryEffect?.Name == "one_hit_ko" ||
            // the move is a self-destruct move
            move.MoveData.SecondaryEffect?.Name == "self_destruct" ||
            move.MoveData.SecondaryEffect?.Name == "explosion");

        if (relevantMoves)
        {
            pokemon.BattleData?.Battle.EventHook.Invoke(new AbilityTriggerEvent(_owner));
        }
    }
}