using UdonSharp;
using UnityEngine;

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemPotMath : UdonSharpBehaviour
{
    // Figure out split and side pots 
    public static int[] DividePot(int seats, int[] contributions, int[] playerRanksByHandValues, int dealerSeat = 0)
    {
        int[] winnings = new int[HoldemGame.MAX_SEATS];

        // Collect all unique non-zero contribution levels
        int numLevels = 0;
        int[] levels = new int[HoldemGame.MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            int c = contributions[i];
            if (c > 0)
            {
                bool exists = false;
                for (int j = 0; j < numLevels; ++j)
                {
                    if (levels[j] == c)
                    {
                        exists = true;
                        break;
                    }
                }
                if (!exists)
                {
                    levels[numLevels++] = c;
                }
            }
        }

        // Sort levels ascending
        for (int i = 1; i < numLevels; ++i)
        {
            int k = levels[i];
            int j = i - 1;
            while (j >= 0 && levels[j] > k)
            {
                levels[j + 1] = levels[j];
                j--;
            }
            levels[j + 1] = k;
        }

        // Deepest stake among live hands; layers above it have no live contender at their own cap
        int maxLiveStake = 0;
        for (int j = 0; j < seats; ++j)
        {
            if (playerRanksByHandValues[j] >= 0 && contributions[j] > maxLiveStake)
            {
                maxLiveStake = contributions[j];
            }
        }

        int[] sharingPlayers = new int[HoldemGame.MAX_SEATS];
        int prevCap = 0;
        for (int L = 0; L < numLevels; ++L)
        {
            int cap = levels[L];
            int layerPot = 0;

            // Calculate chips contributed to this layer (between prevCap and cap)
            for (int j = 0; j < seats; ++j)
            {
                if (contributions[j] > prevCap)
                {
                    layerPot += Mathf.Min(contributions[j], cap) - prevCap;
                }
            }

            if (layerPot <= 0)
            {
                prevCap = cap;
                continue;
            }

            // Uncollected chips above every live stake go to the best live hands as if the layer stopped there
            int reach = Mathf.Min(cap, maxLiveStake);

            int bestRank = int.MaxValue;
            for (int j = 0; j < seats; ++j)
            {
                if (contributions[j] >= reach && playerRanksByHandValues[j] >= 0 && playerRanksByHandValues[j] < bestRank)
                {
                    bestRank = playerRanksByHandValues[j];
                }
            }

            // Sharers in positional order starting from Small Blind
            int sharingCount = 0;
            if (bestRank != int.MaxValue)
            {
                for (int step = 0; step < seats; ++step)
                {
                    int j = (dealerSeat + 1 + step) % seats;
                    if (contributions[j] >= reach && playerRanksByHandValues[j] == bestRank)
                    {
                        sharingPlayers[sharingCount++] = j;
                    }
                }
            }

            if (sharingCount > 0)
            {
                int share = layerPot / sharingCount;
                int remainder = layerPot % sharingCount;

                for (int s = 0; s < sharingCount; ++s)
                {
                    winnings[sharingPlayers[s]] += share;
                }

                // Distribute remaining odd chips 1 by 1 in positional order
                for (int r = 0; r < remainder; ++r)
                {
                    winnings[sharingPlayers[r]] += 1;
                }
            }

            prevCap = cap;
        }

        return winnings;
    }

    public static bool IsBetLegal(int bet, int seatIdx, int callOnlyMask, int currentBet,
        int minimumRaise, int[] stacks, int[] roundContribution)
    {
        if (((callOnlyMask >> seatIdx) & 1) != 0)
            return bet == Mathf.Min(currentBet - roundContribution[seatIdx], stacks[seatIdx]);

        return
            bet <= stacks[seatIdx] &&
            (roundContribution[seatIdx] + bet == currentBet || // call
             bet == stacks[seatIdx] || // all in
             (roundContribution[seatIdx] + bet - currentBet) >= minimumRaise // (re) raise of appropriate size
            );
    }

    // Calculate median stack from players who are ready and stacked
    public static int CalculateMedianStack(int seats, int[] stacks, bool[] playerStackedAndReady)
    {
        // Collect all stacks from ready players
        int[] sortedStacks = new int[HoldemGame.MAX_SEATS];
        int count = 0;
        for (int i = 0; i < seats; i++)
        {
            if (playerStackedAndReady[i])
            {
                sortedStacks[count++] = stacks[i];
            }
        }
        
        if (count == 0) return 0;
        
        // Sort the stacks
        for (int i = 1; i < count; i++)
        {
            int key = sortedStacks[i];
            int j = i - 1;
            while (j >= 0 && sortedStacks[j] > key)
            {
                sortedStacks[j + 1] = sortedStacks[j];
                j--;
            }
            sortedStacks[j + 1] = key;
        }
        
        // Return median (middle value for odd count, average of two middle for even)
        if (count % 2 == 1)
        {
            return sortedStacks[count / 2];
        }
        else
        {
            return (sortedStacks[count / 2 - 1] + sortedStacks[count / 2]) / 2;
        }
    }

    // Calculate big blind from median stack: round up to nearest 10
    public static int CalculateBigBlindFromMedian(int medianStack, int divisor, int minBigBlind)
    {
        if (medianStack <= 0 || divisor <= 0) return minBigBlind;
        
        int rawBigBlind = medianStack / divisor;
        // Round up to nearest multiple of 10
        int roundedBigBlind = ((rawBigBlind + 9) / 10) * 10;
        
        // Ensure minimum big blind
        return Mathf.Max(roundedBigBlind, minBigBlind);
    }
}
