namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Moody is an ability that raises one stat and lowers another at the end of each turn.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Moody_(Ability)">Bulbapedia - Moody</see>
/// </summary>
[Script(ScriptCategory.Ability, "moody")]
public class Moody : Script, IScriptOnEndTurn
{
    private IPokemon? _pokemon;

    /// <inheritdoc />
    public override void OnAddedToParent(IScriptSource source)
    {
        if (source is not IPokemon pokemon)
            throw new InvalidOperationException("Moody script must be attached to a Pokemon.");
        _pokemon = pokemon;
    }

    /// <inheritdoc />
    public void OnEndTurn(IScriptSource owner, IBattle battle)
    {
        if (_pokemon == null)
            return;

        var stats = _pokemon.StatBoost;
        Statistic? raiseStat = null;

        var possibleStatsToRaise = stats.Where(x => x is
                { value: < 6, statistic: not Statistic.Accuracy and not Statistic.Evasion and not Statistic.Hp })
            .Select(x => x.statistic).ToList();
        if (possibleStatsToRaise.Count > 0)
        {
            raiseStat = possibleStatsToRaise[battle.Random.GetInt(possibleStatsToRaise.Count)];
        }

        Statistic? lowerStat = null;
        var possibleStatsToLower = stats.Where(x => x is
        {
            value: > -6,
            statistic: not Statistic.Accuracy and not Statistic.Evasion and not Statistic.Hp,
        } && x.statistic != raiseStat).Select(x => x.statistic).ToList();

        if (possibleStatsToLower.Count > 0)
        {
            lowerStat = possibleStatsToLower[battle.Random.GetInt(possibleStatsToLower.Count)];
        }

        if (raiseStat != null)
            _pokemon.ChangeStatBoost(raiseStat.Value, 1, true, false);
        if (lowerStat != null)
            _pokemon.ChangeStatBoost(lowerStat.Value, -1, true, false);
    }
}