"""Date and time snippets (standard library only, timezone aware)."""
from datetime import date, datetime, timedelta, timezone


def utc_now():
    """Current time as an aware UTC datetime (datetime.utcnow() is deprecated).

    >>> utc_now().tzinfo is timezone.utc
    True
    """
    return datetime.now(timezone.utc)


def parse_iso(text):
    """Parse an ISO 8601 timestamp; a trailing 'Z' is accepted on every Python 3.7+.

    >>> parse_iso('2026-12-01T09:30:00Z')
    datetime.datetime(2026, 12, 1, 9, 30, tzinfo=datetime.timezone.utc)
    """
    if text.endswith('Z'):
        text = text[:-1] + '+00:00'
    return datetime.fromisoformat(text)


def days_between(a, b):
    """Whole days from date ``a`` to date ``b`` (negative if b is earlier).

    >>> days_between(date(2026, 1, 1), date(2026, 12, 1))
    334
    """
    return (b - a).days


def add_business_days(start, n):
    """Add ``n`` weekdays (Mon-Fri) to a date. Holidays are not considered.

    >>> add_business_days(date(2026, 11, 27), 1)  # Friday -> Monday
    datetime.date(2026, 11, 30)
    """
    step = 1 if n >= 0 else -1
    current, left = start, abs(n)
    while left:
        current += timedelta(days=step)
        if current.weekday() < 5:
            left -= 1
    return current


def date_range(start, end, step_days=1):
    """Dates from ``start`` up to and including ``end``.

    >>> [d.day for d in date_range(date(2026, 2, 26), date(2026, 3, 2))]
    [26, 27, 28, 1, 2]
    """
    d = start
    while d <= end:
        yield d
        d += timedelta(days=step_days)


def is_leap_year(year):
    """Gregorian leap year rule.

    >>> [is_leap_year(y) for y in (1900, 2000, 2024, 2026)]
    [False, True, True, False]
    """
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


def age(born, today):
    """Age in whole years on ``today``.

    >>> age(date(2000, 12, 2), date(2026, 12, 1))
    25
    """
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


def human_duration(seconds):
    """Readable duration like '1h 2m 3s'.

    >>> human_duration(3723), human_duration(59), human_duration(90061)
    ('1h 2m 3s', '59s', '1d 1h 1m 1s')
    """
    seconds = int(seconds)
    parts = []
    for unit, size in (('d', 86400), ('h', 3600), ('m', 60), ('s', 1)):
        value, seconds = divmod(seconds, size)
        if value:
            parts.append(f'{value}{unit}')
    return ' '.join(parts) or '0s'


def start_of_week(d):
    """Monday of the week containing ``d``.

    >>> start_of_week(date(2026, 12, 3))
    datetime.date(2026, 11, 30)
    """
    return d - timedelta(days=d.weekday())
