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

// Biggest showdown pot share per player, persisted with the five cards that won it. These tests
// drive the real HoldemGame.UpdatePlayerMetrics path against the fake VRChat runtime.
public class BiggestWinTests
{
    private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;

    // Card ids are suit * 13 + (rank - 2); rank 14 is the ace.
    private const int CLUBS = 0, DIAMONDS = 13, HEARTS = 26, SPADES = 39;
    private static int Card(int suit, int rank) { return suit + rank - 2; }

    private static readonly string AmountKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinAmountV2";
    private static readonly string HandKey = PlayerBalanceComponent.SaveKeyPrefix + "HoldemBigWinCardsV2";

    private GameObject gameGo;
    private HoldemGame game;
    private VrcRuntimeFake fake;
    private PlayerBalanceComponent[] balances;

    [SetUp]
    public void SetUp()
    {
        fake = new VrcRuntimeFake();
        fake.Install(1);
        fake.MasterId = 1;

        gameGo = new GameObject("BiggestWinGame");
        game = gameGo.AddComponent<HoldemGame>();
        game.seats = 10;
        game.isTournamentActive = false;
        game.players = new HoldemPlayer[10];
        balances = new PlayerBalanceComponent[10];
        for (int i = 0; i < 10; i++)
        {
            var pGo = new GameObject("Player_" + i);
            pGo.transform.SetParent(gameGo.transform);
            game.players[i] = pGo.AddComponent<HoldemPlayer>();
            game.players[i].game = game;
            game.players[i].seatIdx = i;
            game.playerState[i] = HoldemGame.PLAYER_DEAD;
        }
    }

    [TearDown]
    public void TearDown()
    {
        fake.Uninstall();
        Object.DestroyImmediate(gameGo);
    }

    private PlayerBalanceComponent Seat(int seatIdx)
    {
        var player = game.players[seatIdx];
        typeof(HoldemPlayer).GetField("activePlayerId", Priv).SetValue(player, -2);
        player.playerReady = true;

        var balanceGo = new GameObject("Balance_" + seatIdx);
        balanceGo.transform.SetParent(gameGo.transform);
        var balance = balanceGo.AddComponent<PlayerBalanceComponent>();
        balance.CurrentSyncedBalance = 10000;
        typeof(PlayerBalanceComponent).GetField("bIsReady", Priv).SetValue(balance, true);
        typeof(HoldemPlayer).GetField("ActivePlayerBalanceComponent", Priv).SetValue(player, balance);
        balances[seatIdx] = balance;
        return balance;
    }

    // PlayerData is one shared fake store, so to tell seats apart only the listed seats' balance
    // components count as owned; everyone else's writes become (ignored) network requests.
    private void OwnOnly(params int[] seatIdxs)
    {
        var owned = new HashSet<GameObject> { gameGo };
        foreach (int s in seatIdxs) owned.Add(balances[s].gameObject);
        fake.IsOwnerOf = go => owned.Contains(go);
    }

    private void Board(int flop0, int flop1, int flop2, int turn, int river)
    {
        var values = new[] { flop0, flop1, flop2, turn, river };
        var names = new[] { "flop0", "flop1", "flop2", "turn", "river" };
        for (int i = 0; i < names.Length; i++) typeof(HoldemGame).GetField(names[i], Priv).SetValue(game, values[i]);
    }

    private void Hole(int seat, int a, int b, int contribution)
    {
        game.holeCards0[seat] = a;
        game.holeCards1[seat] = b;
        game.potContribution[seat] = contribution;
        game.playerState[seat] = HoldemGame.PLAYER_COMMITED;
    }

    // Plays out the transition into TABLE_WINNER the way Transition does, winners included.
    private void Showdown(bool wonByFold = false)
    {
        var pre = (int[])typeof(HoldemGame).GetField("preTransitionPlayerState", Priv).GetValue(game);
        for (int i = 0; i < game.seats; i++) pre[i] = game.playerState[i];

        game.wonByFold = wonByFold;
        game.dealerSeat = 0;
        game.tableState = HoldemGame.TABLE_WINNER;
        typeof(HoldemGame).GetField("preTransitionTableState", Priv).SetValue(game, HoldemGame.TABLE_PLAYING);

        ulong[] values = wonByFold ? null : HoldemHandEvaluator.GetHandValues(
            game.seats, game.playerState, game.holeCards0, game.holeCards1,
            (int)Field("flop0"), (int)Field("flop1"), (int)Field("flop2"), (int)Field("turn"), (int)Field("river"));
        int[] winnings = game.ResolveWinnings(values);
        game.winnerMask = 0;
        for (int i = 0; i < game.seats; i++) if (winnings[i] > 0) game.winnerMask |= 1 << i;

        typeof(HoldemGame).GetMethod("UpdatePlayerMetrics", Priv).Invoke(game, null);
    }

    private object Field(string name) { return typeof(HoldemGame).GetField(name, Priv).GetValue(game); }

    private static int[] Sorted(params int[] cards) { var c = (int[])cards.Clone(); System.Array.Sort(c); return c; }

    private static int[] SortedUnpack(int packed)
    {
        return Sorted(HoldemHandEvaluator.UnpackBestFive(packed));
    }

    private static int ClassOf(int packed)
    {
        int[] c = HoldemHandEvaluator.UnpackBestFive(packed);
        return HoldemHandEvaluator.GetHandClassInt(HoldemHandEvaluator.EvaluateHand(c[0], c[1], c[2], c[3], c[4]));
    }

    private bool WroteBiggestWin()
    {
        return fake.Store.ContainsKey(AmountKey) || fake.Store.ContainsKey(HandKey);
    }

    // Board 2c 7d 9h Jc 4s: no straight or flush is possible.
    private void DryBoard() { Board(Card(CLUBS, 2), Card(DIAMONDS, 7), Card(HEARTS, 9), Card(CLUBS, 11), Card(SPADES, 4)); }

    // ---- end to end through UpdatePlayerMetrics ----

    [Test]
    public void ShowdownWinnerRecordsGrossPotAndTheFiveWinningCards()
    {
        Seat(0); Seat(1);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 1000);   // trip nines
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 1000); // pair of kings
        OwnOnly(0);

        Showdown();

        Assert.AreEqual(2000, fake.Store[AmountKey], "The whole pot is received, not just the profit");
        int packed = (int)fake.Store[HandKey];
        CollectionAssert.AreEqual(
            Sorted(Card(CLUBS, 9), Card(DIAMONDS, 9), Card(HEARTS, 9), Card(CLUBS, 11), Card(DIAMONDS, 7)),
            SortedUnpack(packed), "Trips plus the two best kickers: J and 7");
        Assert.AreEqual(3, ClassOf(packed), "The stored cards re-evaluate as three of a kind");
        Assert.AreEqual(2000, balances[0].GetBiggestWin());
        Assert.AreEqual(packed, balances[0].GetBiggestWinHand());
    }

    [Test]
    public void LosingSeatRecordsNothing()
    {
        Seat(0); Seat(1);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 1000);
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 1000);
        OwnOnly(1); // the loser

        Showdown();

        Assert.IsFalse(WroteBiggestWin(), "A seat that lost the showdown has no win to record");
    }

    [Test]
    public void SplitPotRecordsTheSeatsShareNotTheWholePot()
    {
        Seat(0); Seat(1);
        // Both play the broadway straight on the board.
        Board(Card(CLUBS, 10), Card(DIAMONDS, 11), Card(HEARTS, 12), Card(CLUBS, 13), Card(SPADES, 14));
        Hole(0, Card(SPADES, 2), Card(SPADES, 3), 1500);
        Hole(1, Card(HEARTS, 2), Card(HEARTS, 3), 1500);
        OwnOnly(0);

        Showdown();

        Assert.AreEqual(1500, fake.Store[AmountKey], "Half of the 3000 pot");
        Assert.AreEqual(4, ClassOf((int)fake.Store[HandKey]), "Both play the straight");
    }

    [Test]
    public void SidePotWinnerRecordsOnlyWhatTheyActuallyReceived()
    {
        Seat(0); Seat(1); Seat(2);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 500);    // short all-in, best hand: main pot only
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 1500); // second best: wins the side pot
        Hole(2, Card(CLUBS, 3), Card(DIAMONDS, 5), 1500);
        OwnOnly(0);

        Showdown();

        Assert.AreEqual(1500, fake.Store[AmountKey], "500 from each of three seats; the side pot is not theirs");
        Assert.AreEqual(3, ClassOf((int)fake.Store[HandKey]));
    }

    [Test]
    public void SidePotWinnerRecordsTheirOwnPotAndHand()
    {
        Seat(0); Seat(1); Seat(2);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 500);
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 1500);
        Hole(2, Card(CLUBS, 3), Card(DIAMONDS, 5), 1500);
        OwnOnly(1);

        Showdown();

        Assert.AreEqual(2000, fake.Store[AmountKey]);
        Assert.AreEqual(1, ClassOf((int)fake.Store[HandKey]), "Pair of kings");
        CollectionAssert.Contains(SortedUnpack((int)fake.Store[HandKey]), Card(CLUBS, 13));
        CollectionAssert.Contains(SortedUnpack((int)fake.Store[HandKey]), Card(DIAMONDS, 13));
    }

    [Test]
    public void FoldWinIsNotRecorded()
    {
        Seat(0); Seat(1);
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 500);
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 500);
        game.playerState[1] = HoldemGame.PLAYER_DEAD;
        OwnOnly(0, 1);

        Showdown(wonByFold: true);

        Assert.IsFalse(WroteBiggestWin(), "Only showdown hands count; a fold win has no hand to show");
    }

    [Test]
    public void TournamentWinsAreNotRecorded()
    {
        game.isTournamentActive = true;
        Seat(0); Seat(1);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), 1000);
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), 1000);
        OwnOnly(0, 1);

        Showdown();

        Assert.IsFalse(WroteBiggestWin(), "Tournament chips aren't real money");
    }

    // ---- record semantics ----

    private void PlayShowdownWorth(int pot)
    {
        Seat(0); Seat(1);
        DryBoard();
        Hole(0, Card(CLUBS, 9), Card(DIAMONDS, 9), pot / 2);
        Hole(1, Card(CLUBS, 13), Card(DIAMONDS, 13), pot / 2);
        OwnOnly(0);
        Showdown();
    }

    [Test]
    public void SmallerWinKeepsTheExistingRecord()
    {
        fake.SeedInt(AmountKey, 5000);
        fake.SeedInt(HandKey, 12345);

        PlayShowdownWorth(2000);

        Assert.AreEqual(5000, fake.GetInt(AmountKey));
        Assert.AreEqual(12345, fake.GetInt(HandKey), "The hand must stay with the amount it belongs to");
    }

    [Test]
    public void LargerWinReplacesAmountAndHandTogether()
    {
        fake.SeedInt(AmountKey, 1000);
        fake.SeedInt(HandKey, 12345);

        PlayShowdownWorth(2000);

        Assert.AreEqual(2000, fake.GetInt(AmountKey));
        Assert.AreEqual(3, ClassOf(fake.GetInt(HandKey)));
    }

    [Test]
    public void EqualWinKeepsTheOlderHand()
    {
        fake.SeedInt(AmountKey, 2000);
        fake.SeedInt(HandKey, 12345);

        PlayShowdownWorth(2000);

        Assert.AreEqual(12345, fake.GetInt(HandKey), "A tie doesn't displace the first hand to reach the amount");
    }

    [Test]
    public void SuccessiveHandsOnlyEverRaiseTheRecord()
    {
        Seat(0);
        OwnOnly(0);
        balances[0].RecordBiggestWin(800, 111);
        balances[0].RecordBiggestWin(3000, 222);
        balances[0].RecordBiggestWin(1200, 333);

        Assert.AreEqual(3000, balances[0].GetBiggestWin());
        Assert.AreEqual(222, balances[0].GetBiggestWinHand());
    }

    // ---- network surface ----

    [Test]
    public void NonOwnerSendsARequestInsteadOfWriting()
    {
        Seat(0);
        OwnOnly(); // nobody owns the balance component

        balances[0].RecordBiggestWin(1000, 77);

        Assert.IsFalse(WroteBiggestWin(), "Only the owner may write PlayerData");
    }

    [Test]
    public void MasterRequestIsAppliedByTheOwner()
    {
        Seat(0);
        OwnOnly(0);

        fake.EnterNetworkCall(fake.LocalPlayer); // the local player is master
        try { balances[0].RequestBigWinCards(88); balances[0].RequestBigWinAmount(1500); }
        finally { fake.ExitNetworkCall(); }

        Assert.AreEqual(1500, fake.GetInt(AmountKey));
        Assert.AreEqual(88, fake.GetInt(HandKey));
    }

    [Test]
    public void AmountAndCardsMayArriveInEitherOrder()
    {
        Seat(0);
        OwnOnly(0);

        fake.EnterNetworkCall(fake.LocalPlayer);
        try { balances[0].RequestBigWinAmount(1500); balances[0].RequestBigWinCards(88); }
        finally { fake.ExitNetworkCall(); }

        Assert.AreEqual(1500, fake.GetInt(AmountKey));
        Assert.AreEqual(88, fake.GetInt(HandKey));
    }

    [Test]
    public void OneHalfAloneRecordsNothing()
    {
        Seat(0);
        OwnOnly(0);

        fake.EnterNetworkCall(fake.LocalPlayer);
        try { balances[0].RequestBigWinAmount(1500); }
        finally { fake.ExitNetworkCall(); }

        Assert.IsFalse(WroteBiggestWin(), "The amount waits for its cards, so a lone half never writes a partial record");
    }

    [Test]
    public void ConsecutiveHandsPairTheirOwnAmountAndCards()
    {
        Seat(0);
        OwnOnly(0);

        fake.EnterNetworkCall(fake.LocalPlayer);
        try
        {
            balances[0].RequestBigWinCards(11); balances[0].RequestBigWinAmount(500);
            balances[0].RequestBigWinCards(22); balances[0].RequestBigWinAmount(300);  // smaller: keeps the first
            balances[0].RequestBigWinCards(33); balances[0].RequestBigWinAmount(900);
        }
        finally { fake.ExitNetworkCall(); }

        Assert.AreEqual(900, fake.GetInt(AmountKey));
        Assert.AreEqual(33, fake.GetInt(HandKey), "The hand stays with the amount it belongs to");
    }

    [Test]
    public void RequestFromANonMasterIsIgnored()
    {
        Seat(0);
        OwnOnly(0);
        var stranger = VrcRuntimeFake.MakePlayer(7, "Mallory", false);
        fake.AddPlayer(stranger);

        fake.EnterNetworkCall(stranger);
        try { balances[0].RequestBigWinCards(99); balances[0].RequestBigWinAmount(999999); }
        finally { fake.ExitNetworkCall(); }

        Assert.IsFalse(WroteBiggestWin(), "A player must not be able to forge their own record");

        // and a stranger's half must not pair up with the master's other half later
        fake.EnterNetworkCall(fake.LocalPlayer);
        try { balances[0].RequestBigWinAmount(1500); }
        finally { fake.ExitNetworkCall(); }
        Assert.IsFalse(WroteBiggestWin(), "The stranger's cards were discarded, so the master's amount still waits");
    }

    // ---- packing ----

    [Test]
    public void PackedHandRoundTripsAtTheCardIdExtremes()
    {
        // Wheel straight flush in clubs uses card id 0; the ace-high spade flush uses 51.
        int wheel = HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 14), Card(CLUBS, 2), Card(CLUBS, 3), Card(CLUBS, 4), Card(CLUBS, 5), Card(HEARTS, 9), Card(HEARTS, 11));
        CollectionAssert.AreEqual(
            Sorted(Card(CLUBS, 14), Card(CLUBS, 2), Card(CLUBS, 3), Card(CLUBS, 4), Card(CLUBS, 5)), SortedUnpack(wheel));
        Assert.AreEqual(8, ClassOf(wheel));

        int royal = HoldemHandEvaluator.PackBestFive(
            Card(SPADES, 14), Card(SPADES, 13), Card(SPADES, 12), Card(SPADES, 11), Card(SPADES, 10), Card(CLUBS, 2), Card(CLUBS, 3));
        Assert.AreEqual(51, SortedUnpack(royal)[4]);
        Assert.AreEqual(9, ClassOf(royal));
    }

    [Test]
    public void PackedHandUsesTheBestFiveOfSevenCards()
    {
        // 7 cards, best five is the full house; the stray 2 and 5 are dropped.
        int packed = HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 8), Card(CLUBS, 12), Card(DIAMONDS, 12), Card(SPADES, 2), Card(SPADES, 5));
        CollectionAssert.AreEqual(
            Sorted(Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 8), Card(CLUBS, 12), Card(DIAMONDS, 12)),
            SortedUnpack(packed));
        Assert.AreEqual(6, ClassOf(packed));
    }

    [Test]
    public void PackedHandIsEmptyUntilFiveCardsAreKnown()
    {
        Assert.AreEqual(0, HoldemHandEvaluator.PackBestFive(Card(CLUBS, 8), Card(DIAMONDS, 8), -1, -1, -1, -1, -1));
        Assert.AreEqual(0, HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 2), Card(HEARTS, 3), -1, -1, -1), "four known cards");
        Assert.AreNotEqual(0, HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 2), Card(HEARTS, 3), Card(HEARTS, 9), -1, -1),
            "hole cards plus a flop is five known cards");
    }

    [Test]
    public void PackedHandRecordsHowManyHoleCardsPlay()
    {
        int both = HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 8), Card(DIAMONDS, 8), Card(HEARTS, 8), Card(CLUBS, 12), Card(DIAMONDS, 2), -1, -1);
        int one = HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 8), Card(DIAMONDS, 3), Card(HEARTS, 8), Card(CLUBS, 12), Card(DIAMONDS, 12), Card(SPADES, 2), Card(SPADES, 5));
        int board = HoldemHandEvaluator.PackBestFive(
            Card(CLUBS, 2), Card(DIAMONDS, 3), Card(HEARTS, 10), Card(HEARTS, 9), Card(HEARTS, 8), Card(HEARTS, 7), Card(HEARTS, 6));

        Assert.AreEqual(2, HoldemHandEvaluator.UnpackHoleCount(both));
        Assert.Less(both, 0, "two hole cards set the sign bit");
        Assert.AreEqual(1, HoldemHandEvaluator.UnpackHoleCount(one));
        Assert.AreEqual(Card(CLUBS, 8), HoldemHandEvaluator.UnpackBestFive(one)[0], "the hole card is first");
        Assert.AreEqual(0, HoldemHandEvaluator.UnpackHoleCount(board));
    }
}
