"""Timestamp conversion helpers for gRPC converters."""

from __future__ import annotations

from datetime import UTC, datetime

from google.protobuf.timestamp_pb2 import Timestamp


def datetime_to_proto_timestamp(dt: datetime) -> Timestamp:
    """Convert datetime to protobuf Timestamp.

    Args:
        dt: Datetime to convert (should be timezone-aware).

    Returns:
        Protobuf Timestamp message.
    """
    ts = Timestamp()
    ts.FromDatetime(dt)
    return ts


def proto_timestamp_to_datetime(ts: Timestamp) -> datetime:
    """Convert protobuf Timestamp to datetime.

    Args:
        ts: Protobuf Timestamp message.

    Returns:
        Timezone-aware datetime (UTC).
    """
    return ts.ToDatetime().replace(tzinfo=UTC)


def epoch_seconds_to_datetime(seconds: float) -> datetime:
    """Convert Unix epoch seconds to datetime.

    Args:
        seconds: Unix epoch seconds (float for sub-second precision).

    Returns:
        Timezone-aware datetime (UTC).
    """
    return datetime.fromtimestamp(seconds, tz=UTC)


def datetime_to_epoch_seconds(dt: datetime) -> float:
    """Convert datetime to Unix epoch seconds.

    Args:
        dt: Datetime to convert.

    Returns:
        Unix epoch seconds as float.
    """
    return dt.timestamp()


def iso_string_to_datetime(iso_str: str) -> datetime:
    """Parse ISO 8601 string to datetime.

    Args:
        iso_str: ISO 8601 formatted string.

    Returns:
        Timezone-aware datetime (UTC if no timezone in string).
    """
    dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=UTC)
    return dt


def datetime_to_iso_string(dt: datetime) -> str:
    """Format datetime as ISO 8601 string.

    Args:
        dt: Datetime to format.

    Returns:
        ISO 8601 formatted string with timezone.
    """
    return dt.isoformat()
