namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Forecast is an ability that changes the Pokémon's form depending on the weather.
/// This ability is exclusive to Castform.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Forecast_(Ability)">Bulbapedia - Forecast</see>
/// </summary>
[Script(ScriptCategory.Ability, "forecast")]
public class Forecast : Script, IScriptOnSwitchIn, IScriptOnWeatherChange
{
    private IPokemon? _pokemon;

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

    /// <inheritdoc />
    public void OnSwitchIn(IPokemon pokemon, byte position)
    {
        ChangeForm(pokemon, pokemon.BattleData?.Battle.WeatherName);
    }

    /// <inheritdoc />
    public void OnWeatherChange(IBattle battle, StringKey? weatherName, StringKey? oldWeatherName)
    {
        if (_pokemon is null)
            return;

        ChangeForm(_pokemon, weatherName);
    }

    /// <inheritdoc />
    public override void OnRemove()
    {
        if (_pokemon is null)
            return;

        ChangeForm(_pokemon, null);
    }

    private static void ChangeForm(IPokemon pokemon, StringKey? weather)
    {
        if (pokemon.Species.Name != "castform")
            return;

        if (weather == ScriptUtils.ResolveName<Weather.HarshSunlight>() &&
            pokemon.Species.TryGetForm("sunny", out var sunnyForm) && pokemon.Form != sunnyForm)
        {
            pokemon.ChangeForm(sunnyForm);
        }
        else if (weather == ScriptUtils.ResolveName<Weather.Rain>() &&
                 pokemon.Species.TryGetForm("rainy", out var rainyForm) && pokemon.Form != rainyForm)
        {
            pokemon.ChangeForm(rainyForm);
        }
        else if (weather == ScriptUtils.ResolveName<Weather.Hail>() &&
                 pokemon.Species.TryGetForm("snowy", out var snowyForm) && pokemon.Form != snowyForm)
        {
            pokemon.ChangeForm(snowyForm);
        }
        else if (pokemon.Form != pokemon.Species.GetDefaultForm())
        {
            pokemon.ChangeForm(pokemon.Species.GetDefaultForm());
        }
    }
}