from datetime import datetime, timezone, timedelta

try:
    from zoneinfo import ZoneInfo  # py3.9+
except Exception:
    ZoneInfo = None


def get_tz(tz_name: str):
    if ZoneInfo is not None:
        try:
            return ZoneInfo(tz_name)
        except Exception:
            pass
    # fallback: if Europe/Moscow requested, assume UTC+3 (no DST)
    if tz_name == "Europe/Moscow":
        return timezone(timedelta(hours=3))
    return timezone.utc


def parse_iso_datetime(dt_str: str):
    """
    Parses ISO strings like:
    2026-02-14T11:00:00.000+00:00
    Returns aware datetime or None.
    """
    if not dt_str:
        return None
    try:
        return datetime.fromisoformat(dt_str)
    except Exception:
        try:
            return datetime.fromisoformat(dt_str.replace("Z", "+00:00"))
        except Exception:
            return None


def to_timezone(dt: datetime, tz) -> datetime:
    if dt is None:
        return None
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(tz)


def format_moscow_ymd_hm(dt: datetime) -> str:
    return dt.strftime("%Y-%m-%d %H:%M") if dt else ""


def format_stamp_ddmmyyyy_hhmm(dt: datetime) -> str:
    return dt.strftime("%d-%m-%Y_%H-%M") if dt else ""

