from sqids import Sqids

_sqids = None


def _make_alphabet() -> str:
    import hashlib
    from django.conf import settings

    digest = hashlib.sha256(settings.SECRET_KEY.encode()).hexdigest()
    base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    seed = int(digest[:16], 16)
    shuffled = list(base)
    for i in range(len(shuffled) - 1, 0, -1):
        seed = (seed * 1103515245 + 12345) & 0x7FFFFFFF
        j = seed % (i + 1)
        shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
    return "".join(shuffled)


def get_sqids() -> Sqids:
    global _sqids
    if _sqids is None:
        _sqids = Sqids(
            alphabet=_make_alphabet(),
            min_length=6,
        )
    return _sqids


def encode_scrobble_share(scrobble_id: int, version: int) -> str:
    return get_sqids().encode([scrobble_id, version])


def decode_scrobble_share(sqid: str) -> list[int] | None:
    return get_sqids().decode(sqid)
