"""Jinja2 filters that are extra useful in some kdlj2 applications."""

import datetime

import jinja2

from .errors import DatetimeParseErrorValue
from .fs import parentpath
from .util import str_esc, time_is_past


def is_overdue(date_str: str) -> bool | DatetimeParseErrorValue:
    """
    Check whether a date string represents an 'overdue' (elapsed) date.

    Return whether a string of the format YYYY-MM-DD is in the past. Always returns
    false for strings that do not follow the format correctly.
    """
    try:
        return time_is_past(datetime.datetime.strptime(date_str, "%Y-%m-%d"))
    except ValueError as v:
        return DatetimeParseErrorValue(v)


def setup_filters(env: jinja2.Environment) -> None:
    """Add the default filters from filters.py into a Jinja2 environment."""
    env.filters["str_esc"] = str_esc
    env.filters["parentpath"] = parentpath
    env.filters["is_overdue"] = is_overdue
