from typing import Optional
import base64
import binascii
import logging


def slug_to_int(slug: str) -> Optional[int]:
    """
    Convert the permalink slug back to the integer id.
    Returns ``None`` if slug is not well-formed.
    """
    byt = slug.encode("utf-8")
    try:
        int_bytes = base64.urlsafe_b64decode(byt)
        return int(int_bytes)
    except (binascii.Error, ValueError):
        logging.getLogger(__name__).error("Unable to interpret slug: %s", slug)
        return None