using PkmnLib.Static.Moves;

namespace PkmnLib.Plugin.Gen7.Scripts.Abilities;

/// <summary>
/// Forewarn is an ability that reveals the opponent's move with the highest base power when the Pokémon enters battle.
/// This ability is commonly associated with Drowzee and Hypno.
///
/// <see href="https://bulbapedia.bulbagarden.net/wiki/Forewarn_(Ability)">Bulbapedia - Forewarn</see>
/// </summary>
[Script(ScriptCategory.Ability, "forewarn")]
public class Forewarn : Script, IScriptOnSwitchIn
{
    /// <inheritdoc />
    public void OnSwitchIn(IPokemon pokemon, byte position)
    {
        var battleData = pokemon.BattleData;
        if (battleData == null)
            return;

        var opponents = battleData.Battle.Sides.Where(x => x != battleData.BattleSide).SelectMany(x => x.Pokemon)
            .WhereNotNull();

        var highestPowerMove = opponents.SelectMany(opponent => opponent.Moves).WhereNotNull().Select(move => new
        {
            Move = move,
            Power = GetBasePower(move.MoveData),
        }).OrderByDescending(move => move.Power).FirstOrDefault();

        battleData.Battle.EventHook.Invoke(new AbilityTriggerEvent(pokemon)
        {
            Metadata = new Dictionary<StringKey, object?>
            {
                { "highest_power_move", highestPowerMove?.Move },
                { "power", highestPowerMove?.Power },
            },
        });
    }

    private static byte GetBasePower(IMoveData moveData)
    {
        // OHKO moves (handled by secondary effect)
        if (moveData.SecondaryEffect?.Name == "one_hit_ko")
            return 150;

        return moveData.Name.ToString() switch
        {
            // 150 BP: Specific moves
            "blast_burn" or "eruption" or "water_spout" or "fissure" or "guillotine" or "horn_drill"
                or "sheer_cold" => 150,
            // 120 BP: Counter, Metal Burst, Mirror Coat
            "counter" or "metal_burst" or "mirror_coat" => 120,
            // 80 BP: List of variable power and fixed-damage moves
            "crush_grip" or "dragon_rage" or "electro_ball" or "endeavor" or "final_gambit" or "flail" or "fling"
                or "frustration" or "grass_knot" or "guardian_of_alola" or "gyro_ball" or "heat_crash" or "heavy_slam"
                or "hidden_power" or "low_kick" or "natural_gift" or "natures_madness" or "night_shade" or "present"
                or "psywave" or "punishment" or "return" or "reversal" or "seismic_toss" or "sonic_boom" or "spit_up"
                or "super_fang" or "trump_card" or "wring_out" => 80,
            // 20 BP: Stored Power, Power Trip
            "stored_power" or "power_trip" => 20,
            _ => moveData.BasePower == 0 ? (byte)1 : moveData.BasePower,
        };
    }
}