"""Tiny ULID generator. 26-char Crockford base32, time-sortable."""

from __future__ import annotations

import os
import time


_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"


def new_ulid(now_ms: int | None = None) -> str:
    """Return a fresh ULID. ``now_ms`` is overridable for tests."""
    ms = (now_ms if now_ms is not None else int(time.time() * 1000)) & ((1 << 48) - 1)
    raw = ms.to_bytes(6, "big") + os.urandom(10)
    n = int.from_bytes(raw, "big")
    out = []
    for _ in range(26):
        out.append(_CROCKFORD[n & 31])
        n >>= 5
    return "".join(reversed(out))
