using UdonSharp;
using UnityEngine;
using VRC.SDKBase;

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemBalanceOps : UdonSharpBehaviour
{
    public static PlayerBalanceComponent GetSeatBalanceComponent(HoldemGame game, int SeatIndex)
    {
        if (SeatIndex < 0 || SeatIndex >= game.players.Length || !game.players[SeatIndex])
        {
            return null;
        }

        return game.players[SeatIndex].OwnerPlayerBalanceComponent();
    }

    // Returns true if the player at a given seat has a balance component that is ready to be used.
    // Should be used to check if a player can participate in a round.
    public static bool IsSeatBalanceReady(HoldemGame game, int SeatIndex)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, SeatIndex);
        return BalanceComponent && BalanceComponent.IsReady();
    }

    public static int GetBalanceForSeat(HoldemGame game, int SeatIndex)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, SeatIndex);
        return BalanceComponent ? BalanceComponent.GetBalance() : 0;
    }

    public static void ModifyBalanceForSeat(HoldemGame game, int SeatIndex, int Delta)
    {
        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, SeatIndex);
        if (BalanceComponent)
        {
            BalanceComponent.ModifyBalance(Delta);
        }
    }

    // Balance component to pay a tournament prize or refund into. Resolved from the player id
    // captured at buy-in. Falls back to the live seat for someone who reconnected under a new id
    // and retook their seat by name.
    public static PlayerBalanceComponent GetTournamentBalanceComponent(HoldemGame game, int SeatIndex)
    {
        if (SeatIndex < 0 || SeatIndex >= game.tournamentPlayerIds.Length) return null;

        // -1 unseated, -2 editor, 0 cleared slot; no real player id is non-positive.
        int Id = game.tournamentPlayerIds[SeatIndex];
        if (Id > 0)
        {
            VRCPlayerApi Player = VRCPlayerApi.GetPlayerById(Id);
            if (Player != null && Utilities.IsValid(Player))
            {
                PlayerBalanceComponent Resolved = PlayerBalanceComponent.GetPlayerBalanceComponent(Player);
                if (Resolved) return Resolved;
            }
        }

        return GetSeatBalanceComponent(game, SeatIndex);
    }

    // Credits a tournament prize/refund and books it as profit in one step, so no caller can
    // move the money without also recording it.
    public static void AwardTournamentPayout(HoldemGame game, int SeatIndex, int Amount)
    {
        PlayerBalanceComponent BalanceComponent = GetTournamentBalanceComponent(game, SeatIndex);
        if (!BalanceComponent)
        {
            Debug.Log($"[Holdem] No balance component for seat {SeatIndex}; {Amount} payout dropped");
            return;
        }
        BalanceComponent.ModifyBalance(Amount);
        BalanceComponent.RecordProfit(Amount);
    }

    // Pushes balance back to the balance component.
    public static void UpdatePlayerBalances(int seats, HoldemPlayer[] players, int[] stacks, int[] preTransitionStacks, int[] lastBankBalances)
    {
        for (int Index = 0; Index < seats; Index++)
        {
            HoldemPlayer Player = players[Index];
            if (!Player || !Player.IsSeated())
            {
                continue;
            }

            PlayerBalanceComponent BalanceComponent = Player.OwnerPlayerBalanceComponent();

            if (!BalanceComponent || !BalanceComponent.IsReady())
            {
                continue;
            }

            int BalanceDelta = stacks[Index] - preTransitionStacks[Index];

            if (BalanceDelta != 0)
            {
                // Compute the expected new bank balance (same clamp that ModifyBalance uses).
                int expectedNewBalance = Mathf.Max(0, BalanceComponent.CurrentSyncedBalance + BalanceDelta);

                BalanceComponent.ModifyBalance(BalanceDelta);

                // ModifyBalance sends a network event for non-owners, so CurrentSyncedBalance
                // stays stale until the round-trip completes. Eagerly update our tracking
                // arrays so the next Transition() tick's external-sync loop does not compute
                // a bogus externalDelta and undo the pot award.
                lastBankBalances[Index] = expectedNewBalance;
                BalanceComponent.CurrentSyncedBalance = expectedNewBalance;
            }
        }
    }

    public static void UpdatePlayerMetrics(HoldemGame game, int preTransitionTableState, int[] preTransitionPlayerState, ulong[] handValues)
    {
        // Folds, including the one that ends the hand
        if (preTransitionTableState == HoldemGame.TABLE_PLAYING && (game.tableState == HoldemGame.TABLE_PLAYING || game.tableState == HoldemGame.TABLE_WINNER))
        {
            for (int i = 0; i < game.seats; ++i)
            {
                if (preTransitionPlayerState[i] != HoldemGame.PLAYER_DEAD && game.playerState[i] == HoldemGame.PLAYER_DEAD)
                {
                    Debug.Log($"[Metrics] Seat {i} FOLD recorded");
                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, i);
                    if (BalanceComponent) BalanceComponent._RecordFold();
                }
            }
        }

        // Win or Lose
        if (game.tableState == HoldemGame.TABLE_WINNER && preTransitionTableState != HoldemGame.TABLE_WINNER)
        {
            int[] winnings = game.ResolveWinnings(handValues);

            if (!game.isTournamentActive)
            {
                for (int i = 0; i < game.seats; ++i)
                {
                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, i);
                    if (!BalanceComponent) continue;

                    // Record profit change for all players who contributed to the pot
                    if (game.potContribution[i] > 0)
                    {
                        int netProfit = winnings[i] - game.potContribution[i];
                        BalanceComponent.RecordProfit(netProfit);
                    }
                }
            }

            if (game.wonByFold)
            {
                // Fold-win: the last surviving player gets a win
                for (int i = 0; i < game.seats; ++i)
                {
                    if (game.playerState[i] != HoldemGame.PLAYER_DEAD)
                    {
                        Debug.Log($"[Metrics] Seat {i} WIN (by fold) recorded");
                        PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, i);
                        if (BalanceComponent) BalanceComponent._RecordWin();
                    }
                }
            }
            else
            {
                // Showdown: check winnerMask for wins/losses
                for (int i = 0; i < game.seats; ++i)
                {
                    // Same reasoning as the hand values above: only seats that actually reached
                    // showdown get a hand class and a win/loss.
                    if (game.playerState[i] == HoldemGame.PLAYER_DEAD) continue;

                    PlayerBalanceComponent BalanceComponent = GetSeatBalanceComponent(game, i);
                    if (!BalanceComponent) continue;

                    int handClassInt = HoldemHandEvaluator.GetHandClassInt(handValues[i]);
                    BalanceComponent.RecordHandClass(handClassInt);

                    if ((game.winnerMask & (1 << i)) != 0)
                    {
                        Debug.Log($"[Metrics] Seat {i} WIN (showdown) recorded");
                        BalanceComponent._RecordWin();
                        if (!game.isTournamentActive && winnings[i] > 0)
                        {
                            // Both values go into locals first: with the nested PackedBestFiveForSeat call inside the
                            // argument list, the amount reached RecordBiggestWin as garbage (sent 60, got 0 / 620756992).
                            // Every other record call here passes plain locals.
                            int winAmount = winnings[i];
                            int winCards = game.PackedBestFiveForSeat(i);
                            int potTotal = 0;
                            for (int p = 0; p < game.seats; ++p) potTotal += game.potContribution[p];
                            Debug.Log($"[Metrics] Seat {i} biggest-win SEND: amount {winAmount}, pot {potTotal}, cards packed {winCards}");
                            BalanceComponent.RecordBiggestWin(winAmount, winCards);
                        }
                    }
                    else
                    {
                        Debug.Log($"[Metrics] Seat {i} LOSS (showdown) recorded");
                        BalanceComponent._RecordLoss();
                    }
                }
            }
        }
    }

    public static void UnseatBrokePlayers(HoldemGame game, bool[] playerIsSeated, bool[] playerIsReady)
    {
        if (game.isTournamentMode || !Networking.IsOwner(game.gameObject)) return;
        if (game.tableState != HoldemGame.TABLE_IDLE && game.tableState != HoldemGame.TABLE_READY) return;

        for (int i = 0; i < game.seats; i++)
        {
            if (!playerIsSeated[i] || game.stacks[i] > 0 || !IsSeatBalanceReady(game, i)) continue;
            if (GetBalanceForSeat(game, i) > 0) continue;

            Debug.Log($"[Holdem] seat {i} has no chips left, unseating");
            game.players[i]._ReleaseControl();
            playerIsSeated[i] = false;
            playerIsReady[i] = false;
        }
    }

    public static bool ReconcileBankBalances(HoldemGame game, bool[] playerIsSeated, bool[] playerIsReady,
        int[] lastBankBalances, bool[] bankBaselineSeeded, int[] preTransitionStacks, int[] lastRebuyVersion)
    {
        bool bReceivedBalanceUpdate = false;
        // Chips only join a stack while no hand is being played
        bool betweenHands = game.tableState != HoldemGame.TABLE_PLAYING;

        for (int i = 0; i < game.seats; i++)
        {
            var player = game.players[i];
            bool balanceReady = IsSeatBalanceReady(game, i);
            playerIsSeated[i] = player.IsSeated();
            playerIsReady[i] = player.playerReady && balanceReady;
            bool seatedAndReady = playerIsSeated[i] && balanceReady;

            if (game.isTournamentActive)
            {
                // Stacks belong to the game here: never sync them from the bank or zero them on stand-up
                if (seatedAndReady) lastBankBalances[i] = GetBalanceForSeat(game, i);
            }
            else if (seatedAndReady)
            {
                int bank = GetBalanceForSeat(game, i);
                bool deferCredit = false;
                if (!game.wasSeated[i])
                {
                    game.stacks[i] = Mathf.Min(bank, game.maxBuyIn);
                    game.wasSeated[i] = true;
                    bankBaselineSeeded[i] = true;
                    bReceivedBalanceUpdate = true;
                }
                else if (!bankBaselineSeeded[i])
                {
                    bankBaselineSeeded[i] = true;
                }
                else
                {
                    int externalDelta = bank - lastBankBalances[i];
                    if (externalDelta < 0 && game.stacks[i] > bank)
                    {
                        game.stacks[i] = Mathf.Max(bank, 0);
                        bReceivedBalanceUpdate = true;
                    }
                    else if (externalDelta > 0)
                    {
                        if (!betweenHands)
                        {
                            deferCredit = true;
                        }
                        else if (bank > 0)
                        {
                            game.stacks[i] = Mathf.Min(bank, game.stacks[i] + externalDelta);
                            bReceivedBalanceUpdate = true;
                        }
                    }
                }
                if (!deferCredit) lastBankBalances[i] = bank;
            }
            else if (!playerIsSeated[i])
            {
                // Seated but balance not ready is a race, not a stand-up: only reset when they actually left
                if (game.tableState == HoldemGame.TABLE_PLAYING && game.playerState[i] != HoldemGame.PLAYER_DEAD)
                {
                    game.RecordPokerDepartureFold(i);
                }
                game.stacks[i] = 0;
                game.wasSeated[i] = false;
                bankBaselineSeeded[i] = false;
                // Leaving folds now; a zeroed stack would otherwise read as all-in
                if (game.tableState == HoldemGame.TABLE_PLAYING && game.playerState[i] != HoldemGame.PLAYER_DEAD)
                {
                    Debug.Log($"[Holdem] seat {i} left mid-hand, folding");
                    game.playerState[i] = HoldemGame.PLAYER_DEAD;
                    game.callOnlyMask &= ~(1 << i);
                    bReceivedBalanceUpdate = true;
                }
            }

            // Must be refreshed unconditionally
            preTransitionStacks[i] = game.stacks[i];

            // Process rebuy (master only, cash game), held until the hand is over
            if (!game.isTournamentActive && betweenHands && Networking.IsOwner(game.gameObject) &&
                player.rebuyVersion > lastRebuyVersion[i])
            {
                lastRebuyVersion[i] = player.rebuyVersion;
                int balance = GetBalanceForSeat(game, i);
                int target = Mathf.Min(balance, game.maxBuyIn);
                if (target > game.stacks[i])
                {
                    game.stacks[i] = target;
                    preTransitionStacks[i] = game.stacks[i];
                    lastBankBalances[i] = balance;
                    bReceivedBalanceUpdate = true;
                }
            }
        }

        return bReceivedBalanceUpdate;
    }
}
