"""UUIDv7 generation and external id encoding (TZ 2.2.1 p.2, p.5).

* ``uuid7()`` — RFC 9562 UUIDv7, monotonic within the process (method 1: 12-bit ``rand_a`` counter),
  never goes backwards on clock rollback, 62 random bits in ``rand_b``.
* ``encode("tpl", uuid)`` -> ``tpl_01JC9X8Q7M3K2V4N5P6R7S8T9V`` (prefix + 26 chars Crockford Base32).
* ``decode("tpl", text)`` accepts the prefixed form or the canonical UUID string; raises ``InvalidId``.
"""

from __future__ import annotations

import secrets
import threading
import time
import uuid

_lock = threading.Lock()
_last_ms = 0
_counter = 0

_CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
_DECODE = {ch: i for i, ch in enumerate(_CROCKFORD)}
_DECODE.update({ch.lower(): i for ch, i in list(_DECODE.items())})
_DECODE.update({"O": 0, "o": 0, "I": 1, "i": 1, "L": 1, "l": 1})

PREFIXES = frozenset({"prj", "tpl", "ver", "job", "fil", "ast", "fnt", "key", "ses", "evt", "dlv", "var"})


class InvalidId(ValueError):
    pass


def _now_ms() -> int:
    return time.time_ns() // 1_000_000


def uuid7() -> uuid.UUID:
    global _last_ms, _counter
    with _lock:
        now = _now_ms()
        if now > _last_ms:
            _last_ms = now
            _counter = secrets.randbits(11)  # random start in the lower half of 12 bits
        else:
            _counter += 1
            if _counter > 0xFFF:
                _last_ms += 1  # counter overflow: borrow the next millisecond
                _counter = secrets.randbits(11)
        ts = _last_ms
        rand_a = _counter
    rand_b = secrets.randbits(62)
    value = (ts & 0xFFFFFFFFFFFF) << 80
    value |= 0x7 << 76
    value |= rand_a << 64
    value |= 0b10 << 62
    value |= rand_b
    return uuid.UUID(int=value)


def uuid7_timestamp_ms(u: uuid.UUID) -> int:
    return u.int >> 80


def _b32(n: int) -> str:
    out = []
    for _ in range(26):
        out.append(_CROCKFORD[n & 31])
        n >>= 5
    return "".join(reversed(out))


def encode(prefix: str, value: uuid.UUID | str | None) -> str | None:
    if value is None:
        return None
    u = value if isinstance(value, uuid.UUID) else uuid.UUID(str(value))
    return f"{prefix}_{_b32(u.int)}"


def decode(prefix: str, text: str) -> uuid.UUID:
    if not isinstance(text, str) or not text:
        raise InvalidId("empty id")
    body = text
    if "_" in text:
        pfx, _, body = text.partition("_")
        if pfx != prefix:
            raise InvalidId("wrong prefix")
        if len(body) != 26:
            raise InvalidId("bad length")
        n = 0
        for ch in body:
            if ch not in _DECODE:
                raise InvalidId("bad character")
            n = (n << 5) | _DECODE[ch]
        if n >> 128:
            raise InvalidId("overflow")
        return uuid.UUID(int=n)
    try:
        u = uuid.UUID(body)
    except ValueError as exc:
        raise InvalidId("not a uuid") from exc
    return u
