"""Shared timestamp helpers for coordinator API serialization."""

from __future__ import annotations

from datetime import UTC, datetime


def parse_api_timestamp(value: str | None) -> datetime | None:
    if not value:
        return None
    normalized = value.replace("Z", "+00:00")
    try:
        parsed = datetime.fromisoformat(normalized)
    except ValueError:
        return None
    if parsed.tzinfo is None:
        return parsed.replace(tzinfo=UTC)
    return parsed.astimezone(UTC)


def latest_api_timestamp(*values: str | None) -> str | None:
    parsed = [parse_api_timestamp(value) for value in values]
    present = [value for value in parsed if value is not None]
    if not present:
        return None
    return max(present).isoformat().replace("+00:00", "Z")


def utc_now_iso() -> str:
    return datetime.now(UTC).isoformat().replace("+00:00", "Z")
