# (c) cavaliba.com - data - datetimeutil.py

"""
Shared datetime helpers. Cavaliba stores and serializes timestamps at whole-second
precision - no fractional seconds anywhere (matching the "datetime" dataformat's
canonical format, see fieldtypes/field_datetime.py). Timestamps stay
timezone-aware: the ISO offset is kept so an exported value can be re-imported
(Instance.merge_import() drops a naive last_sync string).

Method inventory: trunc_seconds, now_seconds, iso_seconds.
"""

from django.utils import timezone


def trunc_seconds(dt):
    """Return dt with its microseconds dropped (None passes through)."""

    if dt is None:
        return None
    return dt.replace(microsecond=0)


def now_seconds():
    """Return the current aware datetime, truncated to whole seconds."""

    return trunc_seconds(timezone.now())


def iso_seconds(dt):
    """Return dt as an ISO 8601 string with second precision - offset kept, no
    fractional seconds (e.g. '2026-09-27T10:11:12+00:00'). Callers handle None
    themselves (the empty-cell / null convention differs per export format)."""

    return dt.isoformat(timespec="seconds")
