from datetime import datetime, timedelta, timezone
from typing import Optional
import re

PRESET_H = re.compile(r"^(\d+)h$")
PRESET_D = re.compile(r"^(\d+)d$")

def parse_expires(value: str | None) -> datetime | None:
  """Parse expiration presets or ISO datetime."""
  if not value or value == "never":
    return None

  value = value.strip()
  if not value:
    return None

  if m := PRESET_H.match(value):
    return datetime.now(timezone.utc) + timedelta(hours=int(m.group(1)))
  if m := PRESET_D.match(value):
    return datetime.now(timezone.utc) + timedelta(days=int(m.group(1)))
  try:
    return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
  except Exception:
    return None

def ensure_utc(dt:datetime):
  """Ensure a timezone-aware UTC datetime or None."""
  if dt is None:
    return None
  if dt.tzinfo is None:
    return dt.replace(tzinfo=timezone.utc)
  return dt.astimezone(timezone.utc)
