using UdonSharp;
using UnityEngine;

// poker hand evaluation
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemHandEvaluator : UdonSharpBehaviour
{
    

    public static ulong[] GetHandValues(
            int seats, int[] playerState, int[] holeCards0, int[] holeCards1,
            int flop0, int flop1, int flop2, int turn, int river)
    {
        ulong[] handValues = new ulong[HoldemGame.MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            if (playerState[i] != HoldemGame.PLAYER_DEAD)
            {
                handValues[i] = BestPlayerHand(
                    holeCards0[i], holeCards1[i],
                    flop0, flop1, flop2, turn, river);
            } 
        }
        return handValues;
    }

    // returns 
    public static int[] RankPlayers(int seats, ulong[] handValues)
    {
        ulong[] sortedHandValues = new ulong[HoldemGame.MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            sortedHandValues[i] = handValues[i];
        }

        // sort descending
        for (int i = 1; i < seats; ++i)
        {
            int j = i - 1;
            ulong k = sortedHandValues[i];
            while (j >= 0 && sortedHandValues[j] < k)
            {
                sortedHandValues[j + 1] = sortedHandValues[j];
                j--;
            }
            sortedHandValues[j + 1] = k;
        }

        // write ranks. probably a way to do this within the sorting loop, but
        // I couldn't figure it out
        int[] playerRanksByHandValues = new int[HoldemGame.MAX_SEATS];
        for (int i = 0; i < seats; ++i)
        {
            ulong value = handValues[i];
            if (value == 0UL)
            {
                playerRanksByHandValues[i] = -1; // Dead/Folded player
                continue;
            }
            int rank = -1;
            ulong last = ulong.MaxValue;
            for (int j = 0; j < seats; ++j)
            {
                ulong otherVal = sortedHandValues[j]; 
                if (otherVal == 0UL) break; // Exclude dead/folded players
                if (last != otherVal)
                {
                    rank++;
                    last = otherVal;
                }
                if (otherVal == value)
                {
                    playerRanksByHandValues[i] = rank;
                    break;
                }
            }
        }

        return playerRanksByHandValues;
    }

    public static ulong umax(ulong a, ulong b)
    {
        return a > b ? a : b;
    }

    // there are more efficient ways to do this yes.
    public static ulong BestPlayerHand(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        // 7 choose 5 = 21 combinations
 
        // both hole cards used (5 choose 3 = 10 combinations):
        ulong max =     EvaluateHand(h0, h1, flop0, flop1, flop2);
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, turn));  
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop0, turn, river));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, river)); 
        max = umax(max, EvaluateHand(h0, h1, flop1, turn, river));
        max = umax(max, EvaluateHand(h0, h1, flop2, turn, river));

        // One hole card h0 used (5 choose 4 = 5 combinations):
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, turn)); 
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, river));
        max = umax(max, EvaluateHand(h0, flop0, flop1, turn, river)); 
        max = umax(max, EvaluateHand(h0, flop0, flop2, turn, river)); 
        max = umax(max, EvaluateHand(h0, flop1, flop2, turn, river)); 

        // One hole card h1 used (5 choose 4 = 5 combinations):
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, river));
        max = umax(max, EvaluateHand(h1, flop0, flop1, turn, river));
        max = umax(max, EvaluateHand(h1, flop0, flop2, turn, river));
        max = umax(max, EvaluateHand(h1, flop1, flop2, turn, river));

        // No hole cards (1 choose 1 = 1):
        max = umax(max, EvaluateHand(flop0, flop1, flop2, turn, river));

        return max;
    }

    // ---- Highlight masks ----
    // Cards are numbered by mask bit: 0 hole0, 1 hole1, 2 flop0, 3 flop1, 4 flop2, 5 turn, 6 river.
    // A card below 0 is unrevealed and never selected.

    // The exact 5-card combination that scores best, or 0 while fewer than five cards are known.
    // Among equal-valued combinations the one using more hole cards wins, so owned cards are preferred.
    public static int BestFiveMask(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        int[] c = new int[] { h0, h1, flop0, flop1, flop2, turn, river };
        int known = 0;
        for (int i = 0; i < 7; ++i)
        {
            if (c[i] >= 0) known |= 1 << i;
        }

        int bestMask = 0;
        ulong bestValue = 0UL;
        int bestHoles = -1;
        for (int mask = 31; mask < 128; ++mask)
        {
            if ((mask & known) != mask || PopCount(mask) != 5) continue;

            int[] pick = new int[5];
            int n = 0;
            for (int i = 0; i < 7; ++i)
            {
                if ((mask & (1 << i)) != 0) pick[n++] = c[i];
            }

            ulong value = EvaluateHand(pick[0], pick[1], pick[2], pick[3], pick[4]);
            int holes = PopCount(mask & 3);
            if (value > bestValue || (value == bestValue && holes > bestHoles))
            {
                bestValue = value;
                bestMask = mask;
                bestHoles = holes;
            }
        }
        return bestMask;
    }

    // The best five cards as card ids, 6 bits each in board-index order; 0 while fewer than five are known.
    // A real hand never packs to 0 because five distinct cards can't all be id 0.
    // Bits 30-31 hold how many of the five are hole cards (0-2). Hole cards sit first in board-index order,
    // so they are the first that many unpacked cards. Bit 31 makes the int negative when both are used.
    public static int PackBestFive(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        int mask = BestFiveMask(h0, h1, flop0, flop1, flop2, turn, river);
        if (mask == 0) return 0;

        int[] c = new int[] { h0, h1, flop0, flop1, flop2, turn, river };
        int packed = 0;
        int n = 0;
        for (int i = 0; i < 7; ++i)
        {
            if ((mask & (1 << i)) != 0) packed |= c[i] << (6 * n++);
        }
        packed |= PopCount(mask & 3) << 30;
        return packed;
    }

    public static int UnpackHoleCount(int packed)
    {
        return (packed >> 30) & 3;
    }

    public static int[] UnpackBestFive(int packed)
    {
        int[] cards = new int[5];
        for (int i = 0; i < 5; ++i) cards[i] = (packed >> (6 * i)) & 63;
        return cards;
    }

    // Score of the best five revealed cards, 0 while fewer than five are known.
    public static ulong BestFiveValue(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        int mask = BestFiveMask(h0, h1, flop0, flop1, flop2, turn, river);
        if (mask == 0) return 0UL;

        int[] c = new int[] { h0, h1, flop0, flop1, flop2, turn, river };
        int[] pick = new int[5];
        int n = 0;
        for (int i = 0; i < 7; ++i)
        {
            if ((mask & (1 << i)) != 0) pick[n++] = c[i];
        }
        return EvaluateHand(pick[0], pick[1], pick[2], pick[3], pick[4]);
    }

    // The cards that make the best hand: kickers are dropped, and a high-card hand lights nothing.
    // Preflop (no board revealed) the only hand there is, is a pocket pair.
    public static int HighlightMask(int h0, int h1, int flop0, int flop1, int flop2, int turn, int river)
    {
        if (flop0 < 0 && flop1 < 0 && flop2 < 0 && turn < 0 && river < 0)
        {
            return (h0 >= 0 && h1 >= 0 && h0 % 13 == h1 % 13) ? 3 : 0;
        }

        int five = BestFiveMask(h0, h1, flop0, flop1, flop2, turn, river);
        if (five == 0) return 0;

        int[] c = new int[] { h0, h1, flop0, flop1, flop2, turn, river };
        ulong value = BestFiveValue(h0, h1, flop0, flop1, flop2, turn, river);
        int handClass = GetHandClassInt(value);
        if (handClass == 0) return 0;

        // straights, flushes, full houses and straight flushes use all five cards
        if (handClass != 1 && handClass != 2 && handClass != 3 && handClass != 7) return five;

        // pair / two pair / trips / quads: only ranks that appear more than once
        int[] rankCount = new int[13];
        for (int i = 0; i < 7; ++i)
        {
            if ((five & (1 << i)) != 0) rankCount[c[i] % 13]++;
        }

        int mask = 0;
        for (int i = 0; i < 7; ++i)
        {
            if ((five & (1 << i)) != 0 && rankCount[c[i] % 13] >= 2) mask |= 1 << i;
        }
        return mask;
    }

    private static int PopCount(int v)
    {
        int n = 0;
        while (v != 0)
        {
            v &= v - 1;
            n++;
        }
        return n;
    }

    public static ulong BestPlayerHandTurn(int h0, int h1, int flop0, int flop1, int flop2, int turn)
    {
        ulong max = EvaluateHand(h0, h1, flop0, flop1, flop2);
        max = umax(max, EvaluateHand(h0, h1, flop0, flop1, turn));
        max = umax(max, EvaluateHand(h0, h1, flop0, flop2, turn));
        max = umax(max, EvaluateHand(h0, h1, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h0, flop0, flop1, flop2, turn));
        max = umax(max, EvaluateHand(h1, flop0, flop1, flop2, turn));
        return max;
    }

    // there are better evaluators in:
    // https://www.codingthewheel.com/archives/poker-hand-evaluator-roundup/
    // but this one is mine, and I don't think I stuff any of the table-based lookups
    // into the udon heap reasonably.
    public static ulong EvaluateHand(int a, int b, int c, int d, int e)
    {
        int swap, r0, r1, r2, r3, r4;
        // flush check
        bool flush = true;
        int suit = a / 13;
        if (b / 13 != suit) flush = false;
        else if (c / 13 != suit) flush = false;
        else if (d / 13 != suit) flush = false;
        else if (e / 13 != suit) flush = false;
        // rank sort 
        // 2 bias to diasambiguate "no pair" from 2, 
        // and get numeral cards to line up (2=2, 10=10, 11=J, 12=Q, 13=K, 14=A)
        r0 = a % 13 + 2; 
        r1 = b % 13 + 2;
        if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
        r2 = c % 13 + 2;
        if (r1 > r2)
        {
            swap = r2; r2 = r1; r1 = swap;
            if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
        }
        r3 = d % 13 + 2;
        if (r2 > r3)
        {
            swap = r3; r3 = r2; r2 = swap;
            if (r1 > r2)
            {
                swap = r2; r2 = r1; r1 = swap;
                if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
            }
        }
        r4 = e % 13 + 2;
        if (r3 > r4)
        {
            swap = r4; r4 = r3; r3 = swap;
            if (r2 > r3)
            {
                swap = r3; r3 = r2; r2 = swap;
                if (r1 > r2)
                {
                    swap = r2; r2 = r1; r1 = swap;
                    if (r0 > r1) { swap = r1; r1 = r0; r0 = swap; }
                }
            }
        }
        // wheel straights are ranked lower than other straights so it's a bit weird.
        bool straight = true, wheelStraight = false;
        if (r1 != r0 + 1) straight = false;
        else if (r2 != r1 + 1) straight = false;
        else if (r3 != r2 + 1) straight = false;
        else if (r4 != r3 + 1)
        {
            straight = false;
            // ace-low "wheel" straight
            if (r4 == 14 && r0 == 2)
            {
                wheelStraight = true;
            } 
        }

        int pair0 = 0, pair1 = 0, triple = 0;
        if (!straight)
        {
            // check for same rank
            if (r1 == r0)
            {
                pair0 = r1;
            }
            if (r2 == r1)
            {
                if (pair0 == r1)
                {
                    triple = r2;
                    // zero the first pair so we can detect the second one
                    // consistently
                    pair0 = 0; 
                } else
                {
                    pair0 = r2;
                }
            }
            if (r3 == r2)
            {
                if (triple == r2)
                {
                    pair1 = r3; // quad
                    pair0 = r3;
                } else if (pair0 == r2)
                {
                    triple = r3;
                    pair0 = 0;
                } else if (pair0 == r1)
                {
                    pair1 = r3;
                } else
                {
                    pair0 = r3;
                }
            }
            if (r4 == r3)
            {
                if (triple == r3)
                {
                    pair0 = r4; // quad
                    pair1 = r4; 
                }
                else if (pair1 == r3) // big full house
                {
                    triple = r4;
                    pair1 = 0;
                }
                else if (pair0 == r3)
                {
                    triple = r4;
                    pair0 = 0;
                } else if (pair0 == r2 || pair0 == r1 || triple == r2) // two pair or small full house
                {
                    pair1 = r4;
                } else
                {
                    pair0 = r4;
                }
            }
        }
        
        // 4 bits cover the 13 card ranks 23456789TJQKA , which are  biased upward
        // by 2 so that e.g. "no pair" is represented by '0', and 2 is e.g. a pair
        // of 2s.
        //
        // [1 bit straight flush]
        // [1 bit wheel-straight flush]
        // [1 bit 4 of a kind] (both pairs are the same for the rank)
        // [1 bit full house]
        // [1 bit flush]
        // [1 bit straight]
        // [1 bit wheel-straight] (ranked lower than other straights)
        // [4 bit 3 of a kind]
        // [4 bit 2nd pair (the higher pair rank if present)]
        // [4 bit, 1st pair]
        // [5 x 4 bit kickers (the hand spelled out in rank order)]
        //
        // spelling out the kickers is slightly redundant with the pair cards, but it's
        // at least correct for evaluation (the pair/triple/4 of a kind conditions are higher bits)

        ulong r = (ulong)(straight && flush ? 1 : 0);
        r = (r << 1) + (ulong)(wheelStraight && flush ? 1 : 0);
        r = (r << 1) + (ulong)(pair0 > 0 && pair0 == pair1 ? 1 : 0);
        r = (r << 1) + (ulong)(triple > 0 && (pair0 > 0 || pair1 > 0) ? 1 : 0);
        r = (r << 1) + (ulong)(flush ? 1 : 0);
        r = (r << 1) + (ulong)(straight ? 1 : 0);
        r = (r << 1) + (ulong)(wheelStraight ? 1 : 0);
        r = (r << 4) + (ulong)triple;
        r = (r << 4) + (ulong)pair1;
        r = (r << 4) + (ulong)pair0;

        r = (r << 4) + (ulong)r4;
        r = (r << 4) + (ulong)r3;
        r = (r << 4) + (ulong)r2;
        r = (r << 4) + (ulong)r1;
        r = (r << 4) + (ulong)r0;
        return r;
    }

public static string HandClass(ulong v)
    {
        string[] ranks = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
        int h = (int)(v >> 32);
        int triple = RankNibble(v, 28);
        int pair1 = RankNibble(v, 24);
        int pair0 = RankNibble(v, 20);

        switch (GetHandClassInt(v))
        {
            case 9: return "Royal Flush";
            case 8: return ((h >> 6) & 1) == 1 ? "Straight Flush" : "Straight Flush (Wheel)";
            case 7: return $"Four of a Kind ({ranks[pair0]})";
            case 6: return $"Full House ({ranks[triple]}/{ranks[pair1 > -1 ? pair1 : pair0]})";
            case 5: return "Flush";
            case 4: return ((h >> 1) & 1) == 1 ? "Straight" : "Straight (Wheel)";
            case 3: return $"Three of a Kind ({ranks[triple]})";
            case 2: return $"Two Pairs ({ranks[pair1]}/{ranks[pair0]})";
            case 1: return $"Pair ({ranks[pair0]})";
        }
        return $"High Card ({ranks[RankNibble(v, 16)]})";
    }

    public static int RankNibble(ulong v, int shift)
    {
        return (int)((v >> shift) & 15UL) - 2;
    }

    public static int GetHandClassInt(ulong v)
    {
        int h = (int)(v >> 32);
        if (((h >> 6) & 1) == 1)
        {
            if (((ulong)(v >> 16) & (ulong)15) == (ulong)14) return 9; // Royal Flush
            return 8; // Straight Flush
        }
        if (((h >> 5) & 1) == 1) return 8; // Straight Flush (Wheel)
        if (((h >> 4) & 1) == 1) return 7; // Four of a Kind
        if (((h >> 3) & 1) == 1) return 6; // Full House
        if (((h >> 2) & 1) == 1) return 5; // Flush
        if (((h >> 1) & 1) == 1) return 4; // Straight
        if ((h & 1) == 1) return 4; // Straight (Wheel)
        if (((ulong)(v >> 28) & (ulong)15) > (ulong)0) return 3; // Three of a Kind
        if (((ulong)(v >> 24) & (ulong)15) > (ulong)0) return 2; // Two Pairs
        if (((ulong)(v >> 20) & (ulong)15) > (ulong)0) return 1; // Pair
        return 0; // High Card
    }
}
