import re
from datetime import timedelta

from ui_router.exceptions import EventSchedulingError

_DELAY_RE = re.compile(r"^(\d+)([smhd])$")

_UNIT_MAP: dict[str, str] = {
    "s": "seconds",
    "m": "minutes",
    "h": "hours",
    "d": "days",
}


def parse_delay(delay: str) -> timedelta:
    match = _DELAY_RE.match(delay)
    if not match:
        msg = f"Invalid delay format: {delay}. Expected: <number><unit> (e.g., '10m', '1h', '30s')"
        raise EventSchedulingError(msg)

    value, unit = match.groups()
    kwarg = _UNIT_MAP.get(unit)
    if kwarg is None:
        msg = f"Unknown delay unit: {unit}"
        raise EventSchedulingError(msg)

    return timedelta(**{kwarg: int(value)})
