import datetime
import typing
from pathlib import Path

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

from gallery.easel.core import AppRequest
from gallery.version import __version__

from ...translation import _
from .tag import TagUtil

ContextProcessor = typing.Callable[[AppRequest], dict[str, typing.Any]]


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


def base_context_processor(request: Request) -> dict:
    return {
        "is_widget": is_widget(request),
        "provider": request.query_params.get("provider"),
    }


def build_templates(
    templates_dir: Path | None = None, filters: dict | None = None, context_processor: ContextProcessor | None = None
) -> Jinja2Templates:
    directory = [Path(__file__).parent.parent / "templates"]
    if templates_dir:
        directory.append(templates_dir)
    context_processors: list[ContextProcessor] = [base_context_processor]
    if context_processor:
        context_processors.append(context_processor)
    templates = Jinja2Templates(directory=directory, context_processors=context_processors)
    templates.env.globals.update(
        {
            "_": _,
            "version": __version__,
            "format_date": format_date,
            "datetime": datetime,
            "tag_util": TagUtil,
            "DATE_FORMAT": "E, d MMMM Y",
        }
    )
    if filters:
        templates.env.filters.update(filters)
    return templates
