# src/core/deck.gd
class_name Deck
extends RefCounted

var _cards: Array[Card] = []

static func _suit_for(original_id: int) -> int:
    if original_id == 52:
        return 4
    if original_id == 53:
        return 5
    return original_id % 4

static func _rank_for(original_id: int) -> int:
    if original_id == 52:
        return 15
    if original_id == 53:
        return 16
    return 2 + (original_id / 4)

static func create(seed: int = -1) -> Deck:
    var d := Deck.new()
    d._cards = []
    for deck_idx in range(2):
        for orig_id in range(54):
            var global_id := Card.card_id_from_deck(orig_id, deck_idx)
            var suit := _suit_for(orig_id)
            var rank := _rank_for(orig_id)
            var c := Card.create(orig_id, suit, rank)
            c.card_id = global_id
            d._cards.append(c)
    if seed >= 0:
        d._shuffle_with_seed(seed)
    else:
        d._shuffle_random()
    return d

func _shuffle_with_seed(seed: int) -> void:
    var rng := RandomNumberGenerator.new()
    rng.seed = seed
    for i in range(_cards.size() - 1, 0, -1):
        var j := rng.randi_range(0, i)
        var tmp := _cards[i]
        _cards[i] = _cards[j]
        _cards[j] = tmp

func _shuffle_random() -> void:
    _shuffle_with_seed(Time.get_unix_time_from_system() as int)

func deal(count: int) -> Array[Card]:
    var result: Array[Card] = []
    var actual := mini(count, _cards.size())
    for _i in range(actual):
        result.append(_cards.pop_back())
    return result

func remaining() -> int:
    return _cards.size()
