from pathlib import Path

from babel.dates import format_date
from fastapi import Request
from fastapi.templating import Jinja2Templates

from gallery.version import __version__

from ...translation import _


def is_widget(request: Request) -> bool:
    return request.url.hostname.startswith("weather") or (request.query_params.get("widget") is not None)


def build_templates(templates_dir: Path | None = None, filters: dict | None = None) -> Jinja2Templates:
    directory = [Path(__file__).parent.parent / "templates"]
    if templates_dir:
        directory.append(templates_dir)
    templates = Jinja2Templates(directory=directory)
    templates.env.globals.update(
        {
            "_": _,
            "version": __version__,
            "format_date": format_date,
        }
    )
    templates.env.filters["is_widget"] = is_widget
    if filters:
        templates.env.filters.update(filters)
    return templates
