"""Helpers for working with timezone-aware UTC datetimes."""

from datetime import datetime, timezone

from .support.errors import DomainValidationError


def ensure_utc_datetime(value: datetime | str) -> datetime:
    """Parse/normalize a datetime value to UTC."""

    if isinstance(value, str):
        text = value.strip().replace("Z", "+00:00")
        try:
            parsed = datetime.fromisoformat(text)
        except ValueError as exc:
            raise DomainValidationError(f"Invalid ISO datetime: {value}") from exc
    else:
        parsed = value

    if parsed.tzinfo is None:
        raise DomainValidationError("Expected timezone-aware datetime")

    return parsed.astimezone(timezone.utc)


def isoformat_z(dt: datetime) -> str:
    """Return ISO-8601 string with a trailing Z."""

    if dt.tzinfo is None:
        raise DomainValidationError("Expected timezone-aware datetime")
    return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")


def utc_now() -> datetime:
    """Return current UTC time."""

    return datetime.now(timezone.utc)


__all__ = ["ensure_utc_datetime", "isoformat_z", "utc_now"]
