namespace PkmnLib.Plugin.Gen7.Scripts.Moves;

[Script(ScriptCategory.Move, "last_resort")]
public class LastResort : Script, IScriptPreventMoveSelection
{
    /// <inheritdoc />
    public void PreventMoveSelection(IMoveChoice choice, ref bool prevent)
    {
        var battleData = choice.User.BattleData;
        if (battleData == null)
        {
            prevent = true;
            return;
        }
        var userMoves = choice.User.Moves.WhereNotNull().Where(x => x.MoveData.Name != "last_resort").ToList();
        if (userMoves.Count == 0)
        {
            prevent = true;
            return;
        }

        // Grab all move choices
        var movesForUserSinceEnteringField = battleData.Battle.PreviousTurnChoices
            // Reading backwards
            .Reverse().SelectMany(x => x.Reverse())
            // We only care about move choices since the user entered the field
            .TakeWhile(x => x is not SwitchChoice switchChoice || x.User != switchChoice.SwitchTo).OfType<MoveChoice>()
            // We only care about the user's move choices
            .Where(x => x.User == choice.User)
            // Grab the chosen move, and remove duplicates
            .Select(x => x.ChosenMove).Distinct().ToList();
        if (!userMoves.All(x => movesForUserSinceEnteringField.Contains(x)))
        {
            prevent = true;
        }
    }
}