using PkmnLib.Dynamic.Models;
using PkmnLib.Dynamic.Models.Choices;
using PkmnLib.Static.Moves;
using PkmnLib.Static.Utils;

namespace PkmnLib.Dynamic.AI;

/// <summary>
/// An AI that makes random choices.
/// </summary>
public class RandomAI : PokemonAI
{
    private readonly IRandom _random;

    /// <inheritdoc />
    public RandomAI() : base("Random")
    {
        _random = new RandomImpl();
    }

    /// <inheritdoc />
    public override ITurnChoice GetChoice(IBattle battle, IPokemon pokemon)
    {
        var moves = pokemon.Moves.WhereNotNull().Where(x => x.CurrentPp > 0).ToList();
        while (moves.Count > 0)
        {
            var move = moves[_random.GetInt(moves.Count)];
            var targets = GetValidTargetsForMove(pokemon, move).ToArray();
            if (move.MoveData.Category is MoveCategory.Physical or MoveCategory.Special)
            {
                targets = targets.Where(x => x.side != pokemon.BattleData!.SideIndex).ToArray();
            }
            if (targets.Length == 0)
            {
                moves.Remove(move);
                continue;
            }
            var target = targets[_random.GetInt(targets.Length)];
            var moveTurnChoice = new MoveChoice(pokemon, move, target.side, target.position);
            if (battle.CanUse(moveTurnChoice))
            {
                return moveTurnChoice;
            }
            moves.Remove(move);
        }
        return battle.Library.MiscLibrary.ReplacementChoice(pokemon,
            pokemon.BattleData!.SideIndex == 0 ? (byte)1 : (byte)0, pokemon.BattleData.Position);
    }
}