"""Timestamp utilities for event processing."""
from datetime import datetime, timezone


def format_timestamp(dt: datetime | None) -> str:
    """Format datetime to display string like 'Feb 04, 2026 14:20'.

    Args:
        dt: Datetime object or None

    Returns:
        Formatted string or "Unknown" if dt is None
    """
    if dt is None:
        return "Unknown"
    return dt.strftime("%b %d, %Y %H:%M")


def parse_epoch_ms(ts_value: str | int | None) -> datetime | None:
    """Parse epoch milliseconds to datetime.

    Args:
        ts_value: Epoch timestamp in milliseconds

    Returns:
        Datetime object or None if parsing fails
    """
    if ts_value is None:
        return None

    try:
        ts_ms = int(ts_value)
        return datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc)
    except (ValueError, TypeError, OSError):
        return None


def parse_iso_timestamp(ts_value: str | None) -> datetime | None:
    """Parse ISO format timestamp to datetime.

    Args:
        ts_value: ISO format timestamp string (e.g., "2026-02-04T14:20:00.000Z")

    Returns:
        Datetime object or None if parsing fails
    """
    if not ts_value:
        return None

    try:
        if ts_value.endswith("Z"):
            ts_value = ts_value[:-1] + "+00:00"
        return datetime.fromisoformat(ts_value)
    except (ValueError, TypeError):
        return None
