"""
Timestamp utilities for consistent datetime handling.

Provides timezone-aware UTC timestamps and safe parsing/comparison
for both old (naive) and new (timezone-aware) formats.

This module centralizes all timestamp operations to ensure:
- No deprecation warnings from datetime.utcnow()
- Backward compatibility with existing naive timestamps in the database
- Safe comparisons between old and new timestamp formats
"""

from datetime import datetime, timezone

# Use datetime.UTC for Python 3.11+, fallback for older versions
try:
    UTC = datetime.UTC
except AttributeError:
    UTC = timezone.utc


def utc_now() -> datetime:
    """Return current UTC time as timezone-aware datetime."""
    return datetime.now(UTC)


def utc_now_iso() -> str:
    """Return current UTC time as ISO format string with timezone."""
    return datetime.now(UTC).isoformat()


def utc_timestamp_ms() -> int:
    """Return current UTC time as milliseconds since epoch."""
    return int(datetime.now(UTC).timestamp() * 1000)


def parse_timestamp(ts: str) -> datetime:
    """
    Parse an ISO timestamp string, handling both naive and aware formats.

    Handles:
    - "2026-01-26T04:30:15" (naive, old format)
    - "2026-01-26T04:30:15+00:00" (aware, new format)
    - "2026-01-26T04:30:15Z" (aware, Z suffix)

    Returns timezone-aware datetime in UTC.
    """
    if not ts:
        return datetime.min.replace(tzinfo=UTC)

    # Normalize Z suffix
    ts = ts.replace("Z", "+00:00")

    try:
        dt = datetime.fromisoformat(ts)
        # If naive, assume UTC
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=UTC)
        return dt
    except ValueError:
        return datetime.min.replace(tzinfo=UTC)


def compare_timestamps(ts1: str, ts2: str) -> int:
    """
    Compare two ISO timestamp strings safely.

    Handles mixed formats (naive vs aware) by parsing both
    to timezone-aware datetimes before comparison.

    Args:
        ts1: First ISO timestamp string
        ts2: Second ISO timestamp string

    Returns:
        -1 if ts1 < ts2
         0 if ts1 == ts2
         1 if ts1 > ts2
    """
    dt1 = parse_timestamp(ts1)
    dt2 = parse_timestamp(ts2)

    if dt1 < dt2:
        return -1
    elif dt1 > dt2:
        return 1
    return 0
