from __future__ import annotations

import re
from datetime import timedelta

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


_MULTIPLIERS = {
    "s": 1,
    "m": 60,
    "h": 3600,
    "d": 86400,
}


def parse_duration(value: str) -> timedelta:
    match = _DURATION_RE.match(value.strip())
    if not match:
        raise ValueError("invalid duration format; use <int><s|m|h|d>, e.g. 30m or 7d")

    amount = int(match.group(1))
    unit = match.group(2)
    if amount <= 0:
        raise ValueError("duration must be > 0")

    return timedelta(seconds=amount * _MULTIPLIERS[unit])
