import os
from datetime import datetime, timedelta

import pytz

TZ = os.getenv('TZ', 'UTC')


def now(tz: str = TZ) -> datetime:
    """Returns the current datetime in the specified timezone.

    If no timezone is provided, returns the current datetime in the local timezone.
    """
    return datetime.now(pytz.timezone(tz))


def ttl(
    *,
    start_dt: datetime | None = None,
    tz: str = TZ,
    **kwargs,
) -> int:
    """Calculates the timestamp for a datetime in the future.
    If start_dt is not provided, it uses the current datetime.
    Additional keyword arguments specify the timedelta to add.
    """
    if not start_dt:
        start_dt = now(tz)

    dt = start_dt + timedelta(**kwargs)
    return int(dt.timestamp())


def timestamp(dt: datetime) -> int:
    """Converts a datetime object to a Unix timestamp."""
    return int(dt.timestamp())


def fromisoformat(dt: str) -> datetime | None:
    """Parses a datetime string in ISO 8601 format and returns a datetime object.
    Returns None if the string is not in a valid ISO 8601 format.
    """
    try:
        date = datetime.fromisoformat(dt)
    except ValueError:
        return None
    else:
        return date
