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

// Playstyle stats (VPIP, PFR, 3-bet, fold to 3-bet) driven through the real betting path:
// HoldemGame.AdvanceBetting classifies each action, FinalizePokerStatsHand packs the per-seat masks,
// and PlayerBalanceComponent persists them. Assertions read the public getters the panel uses.
public class PokerStatsEndToEndTests
{
    private const BindingFlags Priv = BindingFlags.NonPublic | BindingFlags.Instance;
    private const int Seats = 4;
    private const int BigBlind = 100;
    private const int Fold = -1;

    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("PokerStatsEndToEnd");
        game = gameGo.AddComponent<HoldemGame>();
        game.seats = Seats;
        game.isTournamentActive = false;
        game.bigBlind = BigBlind;
        game.actionTimeoutSecs = 100000;
        game.players = new HoldemPlayer[HoldemGame.MAX_SEATS];
        balances = new PlayerBalanceComponent[Seats];
        for (int i = 0; i < Seats; i++)
        {
            var playerGo = new GameObject("Player_" + i);
            playerGo.transform.SetParent(gameGo.transform);
            var player = playerGo.AddComponent<HoldemPlayer>();
            player.game = game;
            player.seatIdx = i;
            game.players[i] = player;

            typeof(HoldemPlayer).GetField("activePlayerId", Priv).SetValue(player, -2);
            player.playerReady = true;
            var balanceGo = new GameObject("Balance_" + i);
            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[i] = balance;
        }
    }

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

    // PlayerData is one shared fake store, so each scenario is replayed once per observed seat with
    // only that seat's balance component owned; every other seat's write is an (ignored) network request.
    private PlayerBalanceComponent Observe(int seat, Action play)
    {
        fake.Store.Clear();
        var owned = new System.Collections.Generic.HashSet<GameObject> { gameGo, balances[seat].gameObject };
        fake.IsOwnerOf = go => owned.Contains(go);
        play();
        return balances[seat];
    }

    // Dealer is seat 0, so seat 1 is the small blind, seat 2 the big blind and seat 3 acts first.
    private void StartHand()
    {
        game.dealerSeat = 0;
        game.headsUp = false;
        game.bettingRound = HoldemGame.PREFLOP;
        game.currentBet = BigBlind;
        game.minimumRaise = BigBlind;
        game.callOnlyMask = 0;
        game.lastTransitionMillis = 0;
        for (int i = 0; i < Seats; i++)
        {
            game.playerState[i] = HoldemGame.PLAYER_PENDING;
            game.stacks[i] = 1000;
            game.roundContribution[i] = 0;
            game.potContribution[i] = 0;
        }
        game.stacks[1] -= BigBlind / 2;
        game.roundContribution[1] = BigBlind / 2;
        game.stacks[2] -= BigBlind;
        game.roundContribution[2] = BigBlind;
        game.actingSeat = 3;
        game.playerState[3] = HoldemGame.PLAYER_ACTING;

        var dealt = new bool[HoldemGame.MAX_SEATS];
        for (int i = 0; i < Seats; i++) dealt[i] = true;
        typeof(HoldemGame).GetMethod("BeginPokerStatsHand", Priv).Invoke(game, new object[] { dealt });
    }

    // The acting seat puts in `bet` more chips (or folds with Fold); the game moves the action itself.
    private void Act(int seat, int bet)
    {
        Assert.AreEqual(seat, game.actingSeat, "unexpected seat to act");
        Assert.IsTrue(game.AdvanceBetting(1000, true, bet, true), "action should be accepted");
    }

    private void Finalize()
    {
        typeof(HoldemGame).GetMethod("FinalizePokerStatsHand", Priv).Invoke(game, null);
    }

    // Seat 3 opens to 300, seat 0 calls, seat 1 (small blind) 3-bets to 900, then the rest fold.
    private void PlayThreeBetPot()
    {
        StartHand();
        Act(3, 300);
        Act(0, 300);
        Act(1, 850);
        Act(2, Fold);
        Act(3, Fold);
        Act(0, Fold);
        Finalize();
    }

    // Seat 3 opens to 300 and everyone else folds.
    private void PlayUncontestedOpen()
    {
        StartHand();
        Act(3, 300);
        Act(0, Fold);
        Act(1, Fold);
        Act(2, Fold);
        Finalize();
    }

    [Test]
    public void OpenRaiserCountsVpipAndPfrAndFoldToThreeBet()
    {
        var b = Observe(3, PlayThreeBetPot);

        Assert.AreEqual(1, b.GetTrackedHands());
        Assert.AreEqual(1, b.GetVpipHands());
        Assert.AreEqual(1, b.GetPfrHands());
        Assert.AreEqual(100f, b.GetVPIPPercent());
        Assert.AreEqual(100f, b.GetPFRPercent());
        Assert.AreEqual(0, b.GetThreeBetOpportunities(), "the opener cannot 3-bet its own raise");
        Assert.AreEqual(1, b.GetFoldToThreeBetOpportunities());
        Assert.AreEqual(1, b.GetFoldsToThreeBet());
        Assert.AreEqual(100f, b.GetFoldToThreeBetPercent());
    }

    [Test]
    public void ColdCallerGetsThreeBetOpportunityButNotThreeBet()
    {
        var b = Observe(0, PlayThreeBetPot);

        Assert.AreEqual(1, b.GetVpipHands());
        Assert.AreEqual(0, b.GetPfrHands());
        Assert.AreEqual(1, b.GetThreeBetOpportunities());
        Assert.AreEqual(0, b.GetThreeBets());
        Assert.AreEqual(0f, b.GetThreeBetPercent());
        Assert.AreEqual(0, b.GetFoldToThreeBetOpportunities(), "only the opener is tracked for fold to 3-bet");
    }

    [Test]
    public void ThreeBettorCountsVpipPfrAndThreeBet()
    {
        var b = Observe(1, PlayThreeBetPot);

        Assert.AreEqual(1, b.GetVpipHands());
        Assert.AreEqual(1, b.GetPfrHands());
        Assert.AreEqual(1, b.GetThreeBetOpportunities());
        Assert.AreEqual(1, b.GetThreeBets());
        Assert.AreEqual(100f, b.GetThreeBetPercent());
        Assert.AreEqual(0, b.GetFoldToThreeBetOpportunities());
    }

    [Test]
    public void BigBlindFoldingToThreeBetCountsAsTrackedHandOnly()
    {
        var b = Observe(2, PlayThreeBetPot);

        Assert.AreEqual(1, b.GetTrackedHands());
        Assert.AreEqual(0, b.GetVpipHands());
        Assert.AreEqual(0f, b.GetVPIPPercent());
        Assert.AreEqual(0, b.GetPfrHands());
        Assert.AreEqual(0, b.GetThreeBetOpportunities(), "a 3-bet was already in, so there is no 3-bet to make");
        Assert.AreEqual(0, b.GetFoldToThreeBetOpportunities());
    }

    [Test]
    public void PercentagesAccumulateAcrossHands()
    {
        // Seat 1 3-bets in the first hand, then folds to an open in the second: 1 of 2 opportunities.
        var b = Observe(1, () => { PlayThreeBetPot(); PlayUncontestedOpen(); });

        Assert.AreEqual(2, b.GetTrackedHands());
        Assert.AreEqual(1, b.GetVpipHands());
        Assert.AreEqual(50f, b.GetVPIPPercent());
        Assert.AreEqual(2, b.GetThreeBetOpportunities());
        Assert.AreEqual(1, b.GetThreeBets());
        Assert.AreEqual(50f, b.GetThreeBetPercent());
    }

    [Test]
    public void OpenerFoldToThreeBetPercentUsesOnlyFacedThreeBets()
    {
        // Seat 3 folds to a 3-bet once, then opens uncontested: 1 of 1 opportunities, not 1 of 2 hands.
        var b = Observe(3, () => { PlayThreeBetPot(); PlayUncontestedOpen(); });

        Assert.AreEqual(2, b.GetTrackedHands());
        Assert.AreEqual(2, b.GetPfrHands());
        Assert.AreEqual(1, b.GetFoldToThreeBetOpportunities());
        Assert.AreEqual(100f, b.GetFoldToThreeBetPercent());
    }

    [Test]
    public void OpenerCallingAThreeBetIsAnOpportunityWithoutAFold()
    {
        var b = Observe(3, () =>
        {
            StartHand();
            Act(3, 300);
            Act(0, Fold);
            Act(1, 850);
            Act(2, Fold);
            Act(3, 600); // calls 900 total
            Finalize();
        });

        Assert.AreEqual(1, b.GetFoldToThreeBetOpportunities());
        Assert.AreEqual(0, b.GetFoldsToThreeBet());
        Assert.AreEqual(0f, b.GetFoldToThreeBetPercent());
    }
}
