using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using VRC.SDKBase;

public class MasterHandoffTests
{
    private const BindingFlags Priv = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
    private const int OldMasterId = 1, AliceId = 2, BobId = 3, CarolId = 4, DaveId = 5;

    private VrcRuntimeFake vrc;
    private readonly List<GameObject> spawned = new List<GameObject>();
    private readonly Dictionary<int, VRCPlayerApi> players = new Dictionary<int, VRCPlayerApi>();
    private GameObject gameGo;
    private HoldemGame game;

    [SetUp]
    public void SetUp()
    {
        vrc = new VrcRuntimeFake();
        vrc.Install(AliceId, "Alice");
        vrc.MasterId = OldMasterId;
        players[AliceId] = vrc.LocalPlayer;
        foreach (var id in new[] { OldMasterId, BobId, CarolId, DaveId })
        {
            players[id] = VrcRuntimeFake.MakePlayer(id, "Player" + id, false);
            vrc.AddPlayer(players[id]);
        }

        gameGo = Spawn("Table");
        game = gameGo.AddComponent<HoldemGame>();
        game.seats = 10;
        game.maxBuyIn = 100000;
        game.players = new HoldemPlayer[10];
        for (int i = 0; i < 10; i++)
        {
            var seatGo = Spawn("Seat_" + i, gameGo);
            game.players[i] = seatGo.AddComponent<HoldemPlayer>();
            game.players[i].game = game;
            game.players[i].seatIdx = i;
            vrc.Owners[seatGo] = players[OldMasterId];
        }
        vrc.Owners[gameGo] = players[OldMasterId];
    }

    [TearDown]
    public void TearDown()
    {
        if (vrc != null) vrc.Uninstall();
        vrc = null;
        players.Clear();
        foreach (var go in spawned) if (go) Object.DestroyImmediate(go);
        spawned.Clear();
    }

    private GameObject Spawn(string name, GameObject parent = null)
    {
        var go = new GameObject(name);
        if (parent != null) go.transform.SetParent(parent.transform);
        else spawned.Add(go);
        return go;
    }

    private PlayerBalanceComponent Sit(int seat, int playerId, int bank)
    {
        var seatPlayer = game.players[seat];
        vrc.Owners[seatPlayer.gameObject] = players[playerId];
        seatPlayer.GetType().GetField("activePlayerId", Priv).SetValue(seatPlayer, playerId);
        seatPlayer.playerReady = true;

        var balanceGo = Spawn("Balance_" + seat);
        var balance = balanceGo.AddComponent<PlayerBalanceComponent>();
        balance.CurrentSyncedBalance = bank;
        typeof(PlayerBalanceComponent).GetField("bIsReady", Priv).SetValue(balance, true);
        typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", Priv).SetValue(seatPlayer, balance);
        vrc.PlayerObjects[players[playerId]] = balanceGo;

        game.wasSeated[seat] = true;
        ((int[])typeof(HoldemGame).GetField("lastBankBalances", Priv).GetValue(game))[seat] = bank;
        ((bool[])typeof(HoldemGame).GetField("bankBaselineSeeded", Priv).GetValue(game))[seat] = true;
        Assert.IsTrue(seatPlayer.IsSeated(), "seat " + seat + " should read as occupied");
        return balance;
    }

    private void SyncBankBaselines()
    {
        var baselines = (int[])typeof(HoldemGame).GetField("lastBankBalances", Priv).GetValue(game);
        for (int i = 0; i < game.seats; i++)
        {
            var balance = HoldemBalanceOps.GetSeatBalanceComponent(game, i);
            if (balance) baselines[i] = balance.GetBalance();
        }
    }

    private const int HandId = 5;
    // Hole cards the old master dealt to seats 0-2, high card first, and the salts it sent with them
    private static readonly int[][] Dealt = { new[] { 51, 50 }, new[] { 49, 48 }, new[] { 47, 46 } };
    private static readonly int[][] Salts = { new[] { 11, -12 }, new[] { 21, -22 }, new[] { 31, -32 } };
    private static readonly int[] OldBoard = { 0, 1, 2, 3, 4 };

    private void DealtByOldMaster(int stack, int inThePot, int bettingRound = HoldemGame.FLOP)
    {
        game.tableState = HoldemGame.TABLE_PLAYING;
        game.bettingRound = bettingRound;
        game.handId = HandId;
        for (int i = 0; i < 3; i++)
        {
            game.holeCards0[i] = Dealt[i][0];
            game.holeCards1[i] = Dealt[i][1];
            game.holeCommitments[i] = HoldemCommit.Commit(HandId, i, Dealt[i][0], Dealt[i][1], Salts[i][0], Salts[i][1]);
            game.dealtPlayerIds[i] = game.players[i].ActivePlayerId();
        }
        foreach (var field in new[] { "flop0", "flop1", "flop2", "turn", "river" })
        {
            SetGameField(field, OldBoard[System.Array.IndexOf(BoardFields, field)]);
        }
        // Alice, the local player, received her own cards privately
        var alice = game.players[0];
        foreach (var pair in new[] { new object[] { "privateHandId", HandId }, new object[] { "privateHole0", Dealt[0][0] },
            new object[] { "privateHole1", Dealt[0][1] }, new object[] { "privateSaltA", Salts[0][0] }, new object[] { "privateSaltB", Salts[0][1] } })
        {
            typeof(HoldemPlayer).GetField((string)pair[0], Priv).SetValue(alice, pair[1]);
        }
        game.dealerSeat = 2;
        game.actingSeat = 0;
        game.currentBet = 0;
        game.minimumRaise = 100;
        game.bigBlind = 100;
        for (int i = 0; i < 3; i++)
        {
            game.stacks[i] = stack - inThePot;
            game.potContribution[i] = inThePot;
            game.playerState[i] = i == 0 ? HoldemGame.PLAYER_ACTING : HoldemGame.PLAYER_PENDING;
        }
        game.lastTransitionMillis = game.GetTimeMillis();
    }

    private void MasterLeaves()
    {
        var oldMaster = players[OldMasterId];
        typeof(VRCPlayerApi).GetField("_isValid", Priv).SetValue(oldMaster, false);
        vrc.MasterId = AliceId;
        foreach (var go in new List<GameObject>(vrc.Owners.Keys))
        {
            if (vrc.Owners[go] == oldMaster) vrc.Owners[go] = players[AliceId];
        }
        // The real VRChat event this handoff would fire on the new owner (Alice, local here).
        game.OnOwnershipTransferred(players[AliceId]);

        typeof(HoldemGame).GetField("holdsDeal", Priv).SetValue(game, false);
        // What the synced state tells a client: no hidden hole cards, only the streets already dealt
        for (int i = 0; i < 10; i++)
        {
            game.holeCards0[i] = -1;
            game.holeCards1[i] = -1;
        }
        int[] firstRound = { HoldemGame.FLOP, HoldemGame.FLOP, HoldemGame.FLOP, HoldemGame.TURN, HoldemGame.RIVER };
        for (int i = 0; i < BoardFields.Length; i++)
        {
            if (game.bettingRound < firstRound[i]) SetGameField(BoardFields[i], -1);
        }
        foreach (var local in new[] { "lastBankBalances", "lastRebuyVersion", "preTransitionStacks", "seatWinnings" })
        {
            typeof(HoldemGame).GetField(local, Priv).SetValue(game, new int[10]);
        }
        typeof(HoldemGame).GetField("bankBaselineSeeded", Priv).SetValue(game, new bool[10]);
        for (int i = 0; i < 10; i++)
        {
            typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", Priv).SetValue(game.players[i], null);
        }

        game.OnPlayerLeft(oldMaster);
    }

    private static readonly string[] BoardFields = { "flop0", "flop1", "flop2", "turn", "river" };

    private void SetGameField(string name, int value)
    {
        typeof(HoldemGame).GetField(name, Priv).SetValue(game, value);
    }

    private int[] Board()
    {
        var board = new int[5];
        for (int i = 0; i < 5; i++) board[i] = (int)typeof(HoldemGame).GetField(BoardFields[i], Priv).GetValue(game);
        return board;
    }

    private bool Recovering()
    {
        return (bool)typeof(HoldemGame).GetField("recovering", Priv).GetValue(game);
    }

    private void Report(int playerId, int handId, int card0, int card1, int saltA, int saltB)
    {
        vrc.EnterNetworkCall(players[playerId]);
        try { game.ReportHoleCards(handId, card0, card1, saltA, saltB); }
        finally { vrc.ExitNetworkCall(); }
    }

    private void ReportHonestly(int playerId, int seat)
    {
        Report(playerId, HandId, Dealt[seat][0], Dealt[seat][1], Salts[seat][0], Salts[seat][1]);
    }

    // Every card on the board and in the dealt seats' hands is a real card, used once
    private void AssertCardsDistinct(int seatsDealt)
    {
        var seen = new HashSet<int>();
        var cards = new List<int>(Board());
        for (int i = 0; i < seatsDealt; i++)
        {
            cards.Add(game.holeCards0[i]);
            cards.Add(game.holeCards1[i]);
        }
        foreach (int card in cards)
        {
            Assert.That(card, Is.InRange(0, 51), "unknown card after recovery: " + string.Join(",", cards));
            Assert.IsTrue(seen.Add(card), "card " + card + " dealt twice: " + string.Join(",", cards));
        }
    }

    private int TotalChips(params PlayerBalanceComponent[] banks)
    {
        int total = 0;
        foreach (var bank in banks) total += bank.GetBalance();
        for (int i = 0; i < game.seats; i++)
        {
            total += game.potContribution[i] + game.roundContribution[i];
        }
        return total;
    }

    private void AdvanceSeconds(int seconds)
    {
        vrc.ServerTimeMillis += seconds * 1000;
    }

    private void SeatsReadVacant(params int[] seats)
    {
        foreach (int seat in seats)
        {
            typeof(HoldemPlayer).GetField("activePlayerId", Priv).SetValue(game.players[seat], -1);
        }
    }

    private void SeatsReadOccupiedAgain(int[] seats, int[] playerIds)
    {
        for (int i = 0; i < seats.Length; i++)
        {
            typeof(HoldemPlayer).GetField("activePlayerId", Priv).SetValue(game.players[seats[i]], playerIds[i]);
        }
    }

    [Test]
    public void HandResumesOnceEverySeatedPlayerProvesTheirCards()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);

        MasterLeaves();
        Assert.IsTrue(Recovering(), "the new owner should be collecting cards, not voiding");
        Assert.AreEqual(HandId, game.recoveryHandId, "clients need to see which hand to report");
        Assert.AreEqual(Dealt[0][0], game.holeCards0[0], "the new owner's own cards count straight away");

        ReportHonestly(BobId, 1);
        ReportHonestly(CarolId, 2);
        game._Transition();

        Assert.IsFalse(Recovering());
        Assert.AreEqual(-1, game.recoveryHandId);
        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState, "the hand carries on");
        Assert.AreEqual(HoldemGame.FLOP, game.bettingRound);
        Assert.AreEqual(0, game.actingSeat, "the same seat is still to act");
        for (int i = 0; i < 3; i++)
        {
            Assert.AreEqual(500, game.potContribution[i], "seat " + i + "'s chips stay in the pot");
            Assert.AreEqual(Dealt[i][0], game.holeCards0[i], "seat " + i);
            Assert.AreEqual(Dealt[i][1], game.holeCards1[i], "seat " + i);
        }
        var board = Board();
        CollectionAssert.AreEqual(new[] { 0, 1, 2 }, new[] { board[0], board[1], board[2] }, "the flop everyone saw is kept");
        AssertCardsDistinct(3);
    }

    [Test]
    public void PreflopRecoveryDrawsTheWholeBoardFromUnseenCards()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500, HoldemGame.PREFLOP);

        MasterLeaves();
        ReportHonestly(BobId, 1);
        ReportHonestly(CarolId, 2);
        game._Transition();

        Assert.IsFalse(Recovering());
        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState);
        AssertCardsDistinct(3);
    }

    [Test]
    public void ForgedReportsAreRejected()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();

        // Bob claims better cards with his real salt
        Report(BobId, HandId, 45, 44, Salts[1][0], Salts[1][1]);
        // Carol replays Bob's genuine proof, which only ever counts for her own seat
        Report(CarolId, HandId, Dealt[1][0], Dealt[1][1], Salts[1][0], Salts[1][1]);
        game._Transition();

        Assert.IsTrue(Recovering(), "no forged report should complete the recovery");
        Assert.AreEqual(-1, game.holeCards0[1]);
        Assert.AreEqual(-1, game.holeCards0[2]);

        ReportHonestly(BobId, 1);
        Assert.AreEqual(Dealt[1][0], game.holeCards0[1], "the honest proof still goes through afterwards");
    }

    [Test]
    public void ReportForAnotherHandIsIgnored()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        game.holeCommitments[1] = HoldemCommit.Commit(HandId - 1, 1, Dealt[1][0], Dealt[1][1], Salts[1][0], Salts[1][1]);
        MasterLeaves();

        Report(BobId, HandId - 1, Dealt[1][0], Dealt[1][1], Salts[1][0], Salts[1][1]);

        Assert.AreEqual(-1, game.holeCards0[1]);
    }

    [Test]
    public void BettingIsFrozenWhileRecovering()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        game.actionTimeoutSecs = 5;
        game.handRecoveryTimeoutSecs = 60;
        MasterLeaves();

        AdvanceSeconds(10);
        game._Transition();

        Assert.IsTrue(Recovering());
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, game.playerState[0], "the acting seat must not time out mid-recovery");

        ReportHonestly(BobId, 1);
        ReportHonestly(CarolId, 2);
        game._Transition();
        Assert.AreEqual(HoldemGame.PLAYER_ACTING, game.playerState[0], "and gets a fresh turn once the hand resumes");
    }

    [Test]
    public void VacantSeatIsFoldedAndTheHandResumes()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();
        SeatsReadVacant(2);

        ReportHonestly(BobId, 1);
        game._Transition();

        Assert.IsFalse(Recovering(), "nobody is left to prove seat 2's cards, so it doesn't hold the hand up");
        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState);
        Assert.AreEqual(HoldemGame.PLAYER_DEAD, game.playerState[2]);
        Assert.AreEqual(500, game.potContribution[2], "the folded seat's chips stay in the pot");
        AssertCardsDistinct(2);
    }

    [Test]
    public void RecoveredHandPlaysOutToShowdown()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();
        ReportHonestly(BobId, 1);
        ReportHonestly(CarolId, 2);
        game._Transition();

        // Everyone times out into a check down to the river
        for (int tick = 0; tick < 40 && game.tableState == HoldemGame.TABLE_PLAYING; tick++)
        {
            AdvanceSeconds(game.actionTimeoutSecs + 1);
            game._Transition();
        }

        Assert.AreEqual(HoldemGame.TABLE_WINNER, game.tableState, "the recovered hand never finished");
        int paid = 0;
        for (int i = 0; i < 3; i++) paid += game.seatWinningsSynced[i];
        Assert.AreEqual(1500, paid, "the whole pot goes to the showdown winner(s)");
    }

    [Test]
    public void RecoveryRestartsTheActingPlayersCountdown()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        AdvanceSeconds(12);

        MasterLeaves();

        Assert.AreEqual(game.GetTimeMillis(), game.lastTransitionMillis,
            "the countdown should restart instead of running out on everyone's screen");
    }

    [Test]
    public void ResetDuringRecoveryDropsItInsteadOfRefundingLater()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        game.readyTimeoutSecs = 600;
        MasterLeaves();
        Assert.IsTrue(Recovering());

        game._ResetGame();

        Assert.IsFalse(Recovering(), "the reset settled the hand");
        Assert.AreEqual(-1, game.recoveryHandId);
        Assert.AreNotEqual(HoldemGame.TABLE_UNINITIALIZED, game.tableState, "the table must not stay frozen after a reset");
        var stacksAfterReset = (int[])game.stacks.Clone();

        AdvanceSeconds(game.handRecoveryTimeoutSecs + 1);
        game._Transition();

        CollectionAssert.AreEqual(stacksAfterReset, game.stacks, "a stale recovery refunded the pot a second time");
        Assert.AreNotEqual(HoldemGame.TABLE_PLAYING, game.tableState);
    }

    [Test]
    public void CancellingTheTournamentDuringRecoveryRefundsOnce()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;
        var alice = Sit(0, AliceId, 5000);
        var bob = Sit(1, BobId, 5000);
        var carol = Sit(2, CarolId, 5000);
        vrc.Owners[gameGo] = players[AliceId];
        vrc.MasterId = AliceId;
        game._StartTournament();
        vrc.MasterId = OldMasterId;
        vrc.Owners[gameGo] = players[OldMasterId];
        DealtByOldMaster(10000, 500);
        MasterLeaves();
        Assert.IsTrue(Recovering());

        game._CancelTournament();
        int[] banksAfterCancel = { alice.GetBalance(), bob.GetBalance(), carol.GetBalance() };
        var stacksAfterCancel = (int[])game.stacks.Clone();

        Assert.IsFalse(Recovering());
        Assert.IsFalse(game.isTournamentActive);

        AdvanceSeconds(game.handRecoveryTimeoutSecs + 1);
        game._Transition();

        CollectionAssert.AreEqual(banksAfterCancel, new[] { alice.GetBalance(), bob.GetBalance(), carol.GetBalance() },
            "the cancel refunded the buy-ins; a stale recovery must not pay out again");
        CollectionAssert.AreEqual(stacksAfterCancel, game.stacks);
    }

    [Test]
    public void DealerCommitsEachDealtSeatOverTheFollowingFrames()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        for (int i = 0; i < 3; i++) game.stacks[i] = 10000;
        vrc.Owners[gameGo] = players[AliceId];
        vrc.MasterId = AliceId;
        game.bigBlind = 100;
        game.tableState = HoldemGame.TABLE_READY;
        game.lastTransitionMillis = game.GetTimeMillis() - 60000;

        game._Transition();
        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState);
        for (int i = 0; i < 10; i++) Assert.AreEqual(0L, game.holeCommitments[i], "nothing is hashed during the deal frame");

        var commitNext = typeof(HoldemGame).GetMethod("CommitNextSeat", Priv);
        commitNext.Invoke(game, null);
        Assert.AreNotEqual(0L, game.holeCommitments[0], "one seat per frame");
        Assert.AreEqual(0L, game.holeCommitments[1]);
        commitNext.Invoke(game, null);
        commitNext.Invoke(game, null);

        var saltA = (int[])typeof(HoldemGame).GetField("holeSaltA", Priv).GetValue(game);
        var saltB = (int[])typeof(HoldemGame).GetField("holeSaltB", Priv).GetValue(game);
        for (int i = 0; i < 3; i++)
        {
            Assert.AreEqual(HoldemCommit.Commit(game.handId, i, game.holeCards0[i], game.holeCards1[i], saltA[i], saltB[i]),
                game.holeCommitments[i], "seat " + i + "'s commitment must match the cards and salt it was sent");
        }
        for (int i = 3; i < 10; i++) Assert.AreEqual(0L, game.holeCommitments[i], "empty seat " + i + " was committed");
        CollectionAssert.AreEqual(new[] { AliceId, BobId, CarolId, 0, 0, 0, 0, 0, 0, 0 }, game.dealtPlayerIds,
            "the deal records who each seat's cards went to");
    }

    private void SitsDown(int seat, int playerId)
    {
        vrc.Owners[game.players[seat].gameObject] = players[playerId];
        typeof(HoldemPlayer).GetField("activePlayerId", Priv).SetValue(game.players[seat], playerId);
    }

    [Test]
    public void BystanderSittingInALiveSeatCannotHoldUpTheRecovery()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();

        // Carol left; Dave takes her seat, which is still in the hand
        SitsDown(2, DaveId);
        Assert.IsTrue(game.players[2].IsSeated());
        ReportHonestly(BobId, 1);
        game._Transition();

        Assert.IsFalse(Recovering(), "a seat that changed hands must not be waited on");
        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState, "the hand carries on instead of being voided");
        Assert.AreEqual(HoldemGame.PLAYER_DEAD, game.playerState[2], "the seat's dealt hand is folded");
        Assert.AreEqual(500, game.potContribution[2], "and its chips stay in the pot");
    }

    [Test]
    public void BystanderInALiveSeatCannotReportForIt()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();

        // Even holding Carol's genuine proof, Dave isn't who the seat was dealt to
        SitsDown(2, DaveId);
        Report(DaveId, HandId, Dealt[2][0], Dealt[2][1], Salts[2][0], Salts[2][1]);

        Assert.AreEqual(-1, game.holeCards0[2]);
    }

    [Test]
    public void DealtPlayerWhoSitsBackDownStillCounts()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        MasterLeaves();

        SeatsReadVacant(2);
        ReportHonestly(BobId, 1);
        SitsDown(2, CarolId);
        game._Transition();
        Assert.IsTrue(Recovering(), "Carol is back in her seat, so her cards are still needed");

        ReportHonestly(CarolId, 2);
        game._Transition();

        Assert.IsFalse(Recovering());
        Assert.AreEqual(Dealt[2][0], game.holeCards0[2]);
        Assert.AreNotEqual(HoldemGame.PLAYER_DEAD, game.playerState[2]);
    }

    [Test]
    public void SeatedPlayerWhoNeverReportsVoidsTheHandAfterTheTimeout()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);

        MasterLeaves();
        ReportHonestly(BobId, 1);
        AdvanceSeconds(game.handRecoveryTimeoutSecs + 1);
        game._Transition();

        Assert.IsFalse(Recovering());
        Assert.AreEqual(0, game.potContribution[1], "the voided hand must not keep anyone's chips");
        Assert.AreEqual(10000, game.stacks[1], "seat 1 gets its contribution back");
        Assert.AreNotEqual(HoldemGame.TABLE_PLAYING, game.tableState, "the hand can't be finished without the deck");
        Assert.IsTrue(game.tableState == HoldemGame.TABLE_IDLE || game.tableState == HoldemGame.TABLE_READY,
            "the table should be lining up the next hand, not stuck: " + game.tableState);
    }

    [Test]
    public void CashChipsAreConservedAcrossTheHandoff()
    {
        var alice = Sit(0, AliceId, 10000);
        var bob = Sit(1, BobId, 10000);
        var carol = Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);
        alice.CurrentSyncedBalance = 9500;
        bob.CurrentSyncedBalance = 9500;
        carol.CurrentSyncedBalance = 9500;
        SyncBankBaselines();
        int before = TotalChips(alice, bob, carol);
        Assert.AreEqual(30000, before, "three 10000 banks, 500 of each sitting in the pot");

        MasterLeaves();
        game._Transition();

        Assert.AreEqual(before, TotalChips(alice, bob, carol),
            "the handoff minted or burned chips: banks " + alice.GetBalance() + "/" + bob.GetBalance()
            + "/" + carol.GetBalance() + " stacks " + game.stacks[0] + "/" + game.stacks[1] + "/" + game.stacks[2]);
    }

    [Test]
    public void CashStackStaysCappedAtTheBuyInAcrossTheHandoff()
    {
        game.maxBuyIn = 10000;
        var alice = Sit(0, AliceId, 50000);
        var bob = Sit(1, BobId, 50000);
        var carol = Sit(2, CarolId, 50000);
        DealtByOldMaster(10000, 500);
        alice.CurrentSyncedBalance = 49500;
        bob.CurrentSyncedBalance = 49500;
        carol.CurrentSyncedBalance = 49500;
        SyncBankBaselines();
        int before = TotalChips(alice, bob, carol);

        MasterLeaves();
        game._Transition();
        game._Transition();

        Assert.LessOrEqual(game.stacks[1], game.maxBuyIn,
            "seat 1's whole bank was pulled onto the table past the " + game.maxBuyIn + " buy-in cap");
        Assert.AreEqual(before, TotalChips(alice, bob, carol), "the handoff minted or burned chips");
    }

    [Test]
    public void CashTableDealsAgainAfterTheHandoff()
    {
        Sit(0, AliceId, 10000);
        Sit(1, BobId, 10000);
        Sit(2, CarolId, 10000);
        DealtByOldMaster(10000, 500);

        // Nobody else proves their cards, so the hand is voided and the next one dealt
        MasterLeaves();

        for (int tick = 0; tick < 20 && (game.tableState != HoldemGame.TABLE_PLAYING || game.handId == HandId); tick++)
        {
            AdvanceSeconds(5);
            game._Transition();
        }

        Assert.AreEqual(HoldemGame.TABLE_PLAYING, game.tableState,
            "the table never dealt another hand after the master left");
        for (int i = 0; i < 3; i++)
        {
            Assert.IsTrue(game.players[i].IsSeated(), "seat " + i + " was dropped by the handoff");
            Assert.AreNotEqual(HoldemGame.PLAYER_DEAD, game.playerState[i], "seat " + i + " was not dealt in");
        }
    }

    [Test]
    public void CashStackStaysCappedWhenTheMasterLeavesBetweenHands()
    {
        game.maxBuyIn = 10000;
        var alice = Sit(0, AliceId, 50000);
        var bob = Sit(1, BobId, 50000);
        var carol = Sit(2, CarolId, 50000);
        for (int i = 0; i < 3; i++) game.stacks[i] = 10000;
        game.tableState = HoldemGame.TABLE_IDLE;
        game.bigBlind = 100;
        game.lastTransitionMillis = game.GetTimeMillis();
        SyncBankBaselines();
        int before = TotalChips(alice, bob, carol);
        Assert.AreEqual(150000, before);

        MasterLeaves();
        game._Transition();

        Assert.AreEqual(10000, game.stacks[1],
            "seat 1's whole bank was pulled onto the table past the " + game.maxBuyIn + " buy-in cap");
        Assert.AreEqual(before, TotalChips(alice, bob, carol),
            "the handoff minted chips: banks " + alice.GetBalance() + "/" + bob.GetBalance() + "/" + carol.GetBalance());
    }

    [Test]
    public void TournamentSurvivesTheMasterLeavingMidHand()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;
        Sit(0, AliceId, 5000);
        Sit(1, BobId, 5000);
        Sit(2, CarolId, 5000);
        vrc.Owners[gameGo] = players[AliceId];
        int savedMaster = vrc.MasterId;
        vrc.MasterId = AliceId;
        game._StartTournament();
        vrc.MasterId = savedMaster;
        vrc.Owners[gameGo] = players[OldMasterId];
        Assert.IsTrue(game.isTournamentActive, "tournament should be running before the handoff");

        DealtByOldMaster(10000, 500);

        MasterLeaves();

        Assert.IsTrue(game.isTournamentActive, "the master leaving must not end the tournament");
        Assert.AreEqual(0, game.playerRanks[0], "nobody has finished yet");
    }

    [Test]
    public void TournamentSurvivesSeatsReadingVacantForATick()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;
        Sit(0, AliceId, 5000);
        Sit(1, BobId, 5000);
        Sit(2, CarolId, 5000);
        vrc.Owners[gameGo] = players[AliceId];
        vrc.MasterId = AliceId;
        game._StartTournament();
        Assert.IsTrue(game.isTournamentActive);

        SeatsReadVacant(1, 2);
        game._Transition();

        Assert.IsTrue(game.isTournamentActive, "a one-tick vacancy must not finish the tournament");

        SeatsReadOccupiedAgain(new[] { 1, 2 }, new[] { BobId, CarolId });
        game._Transition();

        Assert.IsTrue(game.isTournamentActive, "tournament should still be running once the seats read back");
        Assert.AreEqual(0, game.playerRanks[0], "nobody has finished yet");
    }

    [Test]
    public void TournamentFinishesOnceOnlyOneSeatStaysVacantPastTheGrace()
    {
        game.isTournamentMode = true;
        game.tournamentBuyIn = 1000;
        game.tournamentStartingStack = 10000;
        Sit(0, AliceId, 5000);
        Sit(1, BobId, 5000);
        Sit(2, CarolId, 5000);
        vrc.Owners[gameGo] = players[AliceId];
        vrc.MasterId = AliceId;
        game._StartTournament();

        game.stacks[0] = 12000;
        game.stacks[1] = 9000;
        game.stacks[2] = 9000;

        SeatsReadVacant(0, 2);
        game._Transition();
        Assert.IsTrue(game.isTournamentActive, "first tick only arms the grace period");

        game.noSeatedActiveSinceMillis = game.GetTimeMillis() - (game.abandonedTournamentTimeoutSecs + 5) * 1000;
        game._Transition();

        Assert.IsFalse(game.isTournamentActive, "a real walkout still has to resolve");
        Assert.AreEqual(HoldemGame.TABLE_IDLE, game.tableState);
        Assert.AreEqual(1, game.playerRanks[1], "the last seat still sitting takes 1st");
        Assert.AreEqual(2, game.playerRanks[0], "the larger of the two abandoned stacks takes 2nd");
        Assert.AreEqual(3, game.playerRanks[2], "the smaller abandoned stack takes 3rd");
    }
}
