from __future__ import annotations

ALPHABET_32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
VALUE_32: dict[str, int] = {ch: i for i, ch in enumerate(ALPHABET_32)}


def mod32_check_character(payload: str) -> str:
    """Compute the Meridian v2 check character for `payload`.

    Implements the Luhn-style MOD 32 algorithm defined in SPEC.md §7.5.

    `payload` MUST be non-empty and MUST contain only characters from
    `ALPHABET_32` (Crockford Base32 canonical alphabet).

    Note: This function is deliberately strict: it does not accept lowercase,
    whitespace, or any visual substitutions.
    """

    if not payload:
        raise ValueError("payload must be non-empty")
    if not payload.isascii():
        raise ValueError("payload must be ASCII")

    s = 0
    factor = 2
    for ch in reversed(payload):
        try:
            v = VALUE_32[ch]
        except KeyError:
            raise ValueError(f"invalid character in payload: {ch!r}") from None

        p = v * factor
        s += (p // 32) + (p % 32)
        factor = 1 if factor == 2 else 2

    check_value = (32 - (s % 32)) % 32
    return ALPHABET_32[check_value]
