using PkmnLib.Dynamic.Libraries;
using PkmnLib.Dynamic.Models;
using PkmnLib.Dynamic.Models.Choices;
using PkmnLib.Dynamic.ScriptHandling;
using PkmnLib.Dynamic.ScriptHandling.Registry;
using PkmnLib.Plugin.Gen7.Scripts.Moves;
using PkmnLib.Plugin.Gen7.Scripts.Pokemon;
using PkmnLib.Static.Moves;
using PkmnLib.Static.Utils;

namespace PkmnLib.Plugin.Gen7.Tests.Scripts.Moves;

/// <summary>
/// Tests for the <see cref="Disable"/> move script and its <see cref="DisableEffect"/>.
/// Gen VII Bulbapedia behavior: "Disable temporarily prevents the target from using a specific move";
/// "Disable now disables the last move that the target used", failing "if the target hasn't used a move
/// yet", and "the effect lasts [...] 4 turns from Generation V onward."
/// </summary>
public class DisableTests
{
    /// <summary>
    /// Creates a mocked move choice whose chosen move has the given name.
    /// </summary>
    private static IMoveChoice CreateMoveChoice(string moveName)
    {
        var moveData = Substitute.For<IMoveData>();
        moveData.Name.Returns(new StringKey(moveName));
        var learnedMove = Substitute.For<ILearnedMove>();
        learnedMove.MoveData.Returns(moveData);
        var choice = Substitute.For<IMoveChoice>();
        choice.ChosenMove.Returns(learnedMove);
        return choice;
    }

    /// <summary>
    /// Creates a fully mocked test setup where the target's volatile scripts are a real
    /// <see cref="ScriptSet"/> and its last used move is the given one (or none).
    /// </summary>
    private static (Disable script, IExecutingMove move, IPokemon target, ScriptSet targetVolatile, IHitData hitData)
        CreateTestSetup(string? lastUsedMove, bool lastMoveIsStruggle = false)
    {
        var script = new Disable();
        var move = Substitute.For<IExecutingMove>();

        var user = Substitute.For<IPokemon>();
        var userBattleData = Substitute.For<IPokemonBattleData>();
        user.BattleData.Returns(userBattleData);
        move.User.Returns(user);

        var target = Substitute.For<IPokemon>();
        var targetVolatile = new ScriptSet(target);
        target.Volatile.Returns(targetVolatile);
        target.GetScripts().Returns(_ => new ScriptIterator(new List<IEnumerable<ScriptContainer>>()));
        var targetBattleData = Substitute.For<IPokemonBattleData>();
        // Create the choice before the Returns call; configuring substitutes inside Returns is not allowed.
        var lastMoveChoice = lastUsedMove == null ? null : CreateMoveChoice(lastUsedMove);
        targetBattleData.LastMoveChoice.Returns(lastMoveChoice);
        target.BattleData.Returns(targetBattleData);

        // Struggle is recognized through the misc library's replacement choice check, not by name.
        var miscLibrary = Substitute.For<IMiscLibrary>();
        var library = Substitute.For<IDynamicLibrary>();
        library.MiscLibrary.Returns(miscLibrary);
        target.Library.Returns(library);
        if (lastMoveChoice != null)
            miscLibrary.IsReplacementChoice(lastMoveChoice).Returns(lastMoveIsStruggle);

        var hitData = Substitute.For<IHitData>();
        move.GetHitData(target, 0).Returns(hitData);

        return (script, move, target, targetVolatile, hitData);
    }

    /// <summary>
    /// Bulbapedia: "Disable now disables the last move that the target used." The target gains the
    /// <see cref="DisableEffect"/> volatile script.
    /// </summary>
    [Test]
    public async Task OnSecondaryEffect_TargetUsedMove_AddsDisableEffectToTarget()
    {
        // Arrange
        var (script, move, target, targetVolatile, _) = CreateTestSetup("tackle");

        // Act
        script.OnSecondaryEffect(move, target, 0);

        // Assert
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsTrue();
    }

    /// <summary>
    /// Bulbapedia: "It fails if the target hasn't used a move yet". Without a last move choice on the
    /// target, the hit fails and no disable is applied.
    /// </summary>
    [Test]
    public async Task OnSecondaryEffect_TargetHasNotUsedMove_FailsHit()
    {
        // Arrange
        var (script, move, target, targetVolatile, hitData) = CreateTestSetup(null);

        // Act
        script.OnSecondaryEffect(move, target, 0);

        // Assert
        hitData.Received(1).Fail();
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsFalse();
    }

    /// <summary>
    /// Bulbapedia: "Disable fails if a move is already disabled". Using Disable on a target that already
    /// has a disabled move must fail the hit rather than silently doing nothing.
    /// </summary>
    [Test]
    public async Task OnSecondaryEffect_TargetAlreadyDisabled_FailsHit()
    {
        // Arrange
        var (script, move, target, targetVolatile, hitData) = CreateTestSetup("tackle");
        targetVolatile.Add(new DisableEffect(new StringKey("growl")));

        // Act
        script.OnSecondaryEffect(move, target, 0);

        // Assert
        hitData.Received(1).Fail();
        await Assert.That(hitData.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "Fail")).IsTrue();
    }

    /// <summary>
    /// Bulbapedia: "It fails if the target hasn't used a move yet or used Struggle". A target whose last
    /// move was Struggle (a replacement choice per <see cref="IMiscLibrary.IsReplacementChoice"/>) cannot
    /// have it disabled.
    /// </summary>
    [Test]
    public async Task OnSecondaryEffect_TargetLastUsedStruggle_FailsHit()
    {
        // Arrange
        var (script, move, target, targetVolatile, hitData) = CreateTestSetup("struggle", true);

        // Act
        script.OnSecondaryEffect(move, target, 0);

        // Assert
        hitData.Received(1).Fail();
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsFalse();
    }

    /// <summary>
    /// Technical test: without battle data on the user (outside of battle) the effect does nothing and
    /// does not throw.
    /// </summary>
    [Test]
    public async Task OnSecondaryEffect_UserHasNoBattleData_DoesNothing()
    {
        // Arrange
        var (script, move, target, targetVolatile, _) = CreateTestSetup("tackle");
        move.User.BattleData.Returns((IPokemonBattleData?)null);

        // Act
        script.OnSecondaryEffect(move, target, 0);

        // Assert
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsFalse();
    }

    /// <summary>
    /// Bulbapedia: "Disable temporarily prevents the target from using a specific move." Selecting the
    /// disabled move is prevented by the <see cref="DisableEffect"/>.
    /// </summary>
    [Test]
    public async Task PreventMoveSelection_ChoiceIsDisabledMove_PreventsSelection()
    {
        // Arrange
        var effect = new DisableEffect(new StringKey("tackle"));
        var choice = CreateMoveChoice("tackle");
        var prevent = false;

        // Act
        effect.PreventMoveSelection(choice, ref prevent);

        // Assert
        await Assert.That(prevent).IsTrue();
    }

    /// <summary>
    /// Bulbapedia: only the disabled move is prevented; the target's other moves remain selectable.
    /// </summary>
    [Test]
    public async Task PreventMoveSelection_ChoiceIsOtherMove_DoesNotPreventSelection()
    {
        // Arrange
        var effect = new DisableEffect(new StringKey("tackle"));
        var choice = CreateMoveChoice("growl");
        var prevent = false;

        // Act
        effect.PreventMoveSelection(choice, ref prevent);

        // Assert
        await Assert.That(prevent).IsFalse();
    }

    /// <summary>
    /// Bulbapedia: "The effect lasts [...] 4 turns from Generation V onward." After three end-of-turn
    /// ticks the effect is still active.
    /// </summary>
    [Test]
    public async Task OnEndTurn_ThreeTurnsPassed_EffectStillActive()
    {
        // Arrange
        var target = Substitute.For<IPokemon>();
        var targetVolatile = new ScriptSet(target);
        target.GetScripts().Returns(_ => new ScriptIterator(new List<IEnumerable<ScriptContainer>>()));
        var effect = new DisableEffect(new StringKey("tackle"));
        targetVolatile.Add(effect);
        var battle = Substitute.For<IBattle>();

        // Act
        for (var i = 0; i < 3; i++)
            effect.OnEndTurn(target, battle);

        // Assert
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsTrue();
    }

    /// <summary>
    /// Bulbapedia: "The effect lasts [...] 4 turns from Generation V onward." After the fourth
    /// end-of-turn tick the effect removes itself.
    /// </summary>
    [Test]
    public async Task OnEndTurn_FourTurnsPassed_EffectRemovesItself()
    {
        // Arrange
        var target = Substitute.For<IPokemon>();
        var targetVolatile = new ScriptSet(target);
        target.GetScripts().Returns(_ => new ScriptIterator(new List<IEnumerable<ScriptContainer>>()));
        var effect = new DisableEffect(new StringKey("tackle"));
        targetVolatile.Add(effect);
        var battle = Substitute.For<IBattle>();

        // Act
        for (var i = 0; i < 4; i++)
            effect.OnEndTurn(target, battle);

        // Assert
        await Assert.That(targetVolatile.Contains(ScriptUtils.ResolveName<DisableEffect>())).IsFalse();
    }
}