import re
from datetime import timedelta
import secrets

TIME_FMT_RE = re.compile(r"(\d+)([sSmMhHdDwW]?)")


def parse_td(text: str) -> timedelta:
    """
    Parse a relative time formatted as specified in the sshd_config man page,
    section TIME FORMATS. Yields a datetime.timedelta.
    """
    td = timedelta()

    for amount, unit in TIME_FMT_RE.findall(text):
        amount = int(amount)
        match unit:
            case "" | "s" | "S":
                td += timedelta(seconds=amount)
            case "m" | "M":
                td += timedelta(minutes=amount)
            case "h" | "H":
                td += timedelta(hours=amount)
            case "d" | "D":
                td += timedelta(days=amount)
            case "w" | "W":
                td += timedelta(weeks=amount)

    return td


def generate_access_token() -> str:
    return secrets.token_urlsafe(16)
